Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

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. The syntax is absolutely right, I have checked it million times. What's wrong?

question from:https://stackoverflow.com/questions/66056878/i-need-help-fixing-a-program-to-solve-the-philosophers-dining-problem

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.

You could eliminate the if statement like this:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...