我的布尔变量无法解析为我的while语句中的变量

问题描述 投票:0回答:3

我想制作一个重复自己的代码,直到用户输入单词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 );
java if-statement boolean do-while
3个回答
1
投票

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

0
投票

你试图在声明它的循环体范围之外读取error3的值:

while(error3 == true);

只需在循环之前声明它:

boolean error3 = true;
do {
    //...
    error3 = (error2 || error1) == true; 
    //...
}
while(error3 == true);

0
投票

因为你在do-while循环中定义了变量。做这个:

boolean error3=true;
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) == 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);
© www.soinside.com 2019 - 2024. All rights reserved.