首页 > 解决方案 > 我的布尔变量无法解析为我的 while 语句中的变量

问题描述

我想制作一个重复自己的代码,直到用户输入单词 Game 或单词 Balance。我做了一个do while循环,但我的 while 语句出现错误。错误是:error3 cannot be resolved into a variable。有谁知道我的代码有什么问题?

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 );

标签: javaif-statementbooleando-while

解决方案


error3do范围内定义。将其声明移出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);

推荐阅读