JAVA非法启动类型

JAVA非法启动类型

本文介绍了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:非法启动类型。语法是绝对正确的,我已经检查了数百万次。怎么了?

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?

推荐答案

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

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

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:

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.

这篇关于JAVA非法启动类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:31