[英]JAVA illegal start of type
My program:我的程序:
public class m
{
public static void main (String[] args)
{
boolean bool = true;
while(bool)
{
rand_number player_1 = new rand_number();
System.out.println("Player_1 guessed " + player_1.rand_n);
rand_number player_2 = new rand_number();
System.out.println("Player_2 guessed " + player_2.rand_n);
rand_number player_3 = new rand_number();
System.out.println("Player_3 guessed " + player_3.rand_n);
if(player_1.guessed || player_2.guessed || player_3.guessed)
{
System.out.println("We have a winner");
bool = false;
}
}
}
}
class rand_number
{
int rand_n = (int)(Math.random() * 10);
if(rand_n == 2)
{
boolean guessed = true;
}
}
I'm getting this error: m.java:31: illegal start of type
.我收到此错误:
m.java:31: illegal start of type
。 The syntax is absolutely right, I have checked it million times.语法绝对正确,我已经检查了数百万次。 What's wrong?
怎么了?
class rand_number
{
//...
if(rand_n == 2)
{
boolean guessed = true;
}
}
You can only have field declarations at the class level.您只能在类级别进行字段声明。 An if statement like this needs to be in a method, constructor, or initializer block.
像这样的 if 语句需要在方法、构造函数或初始化程序块中。
You could eliminate the if statement like this:您可以像这样消除 if 语句:
boolean guessed = rand_n == 2;
But I question why you have any desire to set this value at creation time at all, as opposed to in response to some user action.但是我质疑您为什么想要在创建时设置此值,而不是响应某些用户操作。
Your syntax is absolutely wrong.你的语法完全错误。
rand_number
doesn't contains methods and yet tries to do conditions. rand_number
不包含方法,但会尝试执行条件。
If you want to do random numbers you should try the Random
class like this :如果你想做随机数,你应该像这样尝试
Random
类:
Random random = new Random();
int numberToFind = random.nextInt(2);
You should take a look at the Java naming conventions , it helps to have a clean code that any java developer can understand in a second.您应该查看Java 命名约定,它有助于拥有任何 Java 开发人员都可以在一秒钟内理解的干净代码。 For example, start your classes names with an uppercase.
例如,类名以大写开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.