JAVA非法启动类型

时间:2010-09-06 18:36:09

标签: java

我的节目:

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;
    }
}

我收到此错误:m.java:31: illegal start of type。语法是绝对正确的,我已经检查了数百万次。怎么了?

2 个答案:

答案 0 :(得分:11)

class rand_number
{
    //...    
    if(rand_n == 2) 
    {
        boolean guessed = true;
    }
}

您只能在班级获得字段声明。像这样的if语句需要在方法,构造函数或初始化块中。

您可以删除if语句:

boolean guessed = rand_n == 2;

但是我怀疑为什么你想要在创建时设置这个值,而不是响应某些用户操作。

答案 1 :(得分:5)

你的语法是完全错误的。 rand_number不包含方法,但仍尝试执行条件。


如果你想做随机数,你应该尝试这样的Random类:

Random random = new Random();
int numberToFind = random.nextInt(2);

你应该看看Java naming conventions,它有助于拥有任何java开发人员可以在一秒钟内理解的干净代码。例如,使用大写字母启动类名称。