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

时间:2019-02-16 22:43:21

标签: java if-statement boolean do-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 );

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

您正在尝试在声明循环体的范围之外读取error3的值:

while(error3 == true);

在循环之前简单地声明它:

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

答案 2 :(得分: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);