Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA illegal start of type

Tags:

java

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?

like image 468
good_evening Avatar asked Sep 06 '10 18:09

good_evening


1 Answers

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.

like image 56
Mark Peters Avatar answered Oct 12 '22 07:10

Mark Peters