我的程序:

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。语法绝对正确,我已经检查了一百万遍了。怎么了?

最佳答案

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

您只能在类级别具有字段声明。这样的if语句必须位于方法,构造函数或初始化程序块中。

您可以消除这样的if语句:
boolean guessed = rand_n == 2;

但是我质疑为什么您根本不想在创建时设置此值,而不是响应某些用户操作。

09-27 20:57