JAVA 非法启动类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3653625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAVA illegal start of type
提问by good_evening
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
. The syntax is absolutely right, I have checked it million times. What's wrong?
我收到此错误:m.java:31: illegal start of type
。语法绝对正确,我已经检查了数百万次。怎么了?
采纳答案by Mark Peters
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.
但是我质疑您为什么想要在创建时设置此值,而不是响应某些用户操作。
回答by Colin Hebert
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. For example, start your classes names with an uppercase.
您应该查看Java 命名约定,它有助于拥有任何 Java 开发人员都可以在一秒钟内理解的干净代码。例如,类名以大写开头。