gpt4 book ai didi

java - 我的 boolean 变量无法解析为 while 语句中的变量

转载 作者:行者123 更新时间:2023-12-02 10:15:17 24 4
gpt4 key购买 nike

我想制作一个重复自身的代码,直到用户键入“游戏”一词或“平衡”一词。我做了一个 do while 循环,但 while 语句出现错误。错误是:error3 无法解析为变量。有谁知道我的代码有什么问题吗?

System.out.println("welcome to Roll the Dice!");
System.out.println("What is your name?");

Scanner input = new Scanner(System. in );
String Name = input.nextLine();

System.out.println("Welcome " + Name + "!");
System.out.println("Do you want to play a game or do you want to check your account's balance?");
System.out.println("For the game typ: Game. For you accounts balance typ: Balance");

do {
String Choice = input.nextLine();
String Balance = "Balance";
String Game = "Game";
input.close();

boolean error1 = !new String(Choice).equals(Game);
boolean error2 = !new String(Choice).equals(Balance);
boolean error3 = (error2 || error1) == true;

if (new String(Choice).equals(Game)) {
System.out.println("Start the game!");
}

else if (new String(Choice).equals(Balance)) {
System.out.println("Check the balance");
}

else {
System.out.println("This is not an correct answer");
System.out.println("Typ: Game to start a game. Typ: Balance to see your account's balance");
}
}
while ( error3 == true );

最佳答案

error3定义在 do 内范围。将其声明移至 do 之外范围并设置里面的值:

    boolean error3 = false;
do {
String Choice = input.nextLine();
String Balance = "Balance";
String Game = "Game";
input.close();

boolean error1 = ! new String(Choice).equals(Game);
boolean error2 = ! new String(Choice).equals(Balance);
error3 = error2 || error1;

另请注意,您可以简化 (error2 || error1) == true简单地说error2 || error1 。您的 while 也可以这样做声明:

while(error3);

关于java - 我的 boolean 变量无法解析为 while 语句中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54728416/

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