java启动类,JAVA非法启动类型

博主在Java程序中遇到while循环内的随机数类(rand_number)中的if语句错误,指出该语句应在方法、构造器或初始化块中。解决方法是移除if,将布尔值直接设置为判断条件。讨论了为何不建议在创建对象时立即设置这个值。
摘要由CSDN通过智能技术生成

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值