gpt4 book ai didi

JAVA非法启动类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:46:25 25 4
gpt4 key购买 nike

我的程序:

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: 非法类型开始。语法绝对正确,我已经检查了一百万次。怎么了?

最佳答案

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

您只能在类级别进行字段声明。像这样的 if 语句需要在方法、构造函数或初始化程序 block 中。

你可以像这样删除 if 语句:

boolean guessed = rand_n == 2;

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

关于JAVA非法启动类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3653625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com