简体   繁体   中英

Do while loop error (switch statement)

I am a beginner to java and trying to implement a do while loop for a number of cases within a switch statement.

    do {

        switch (UserInput){
        case "a2":
        case "a3":
        case "b1":
        case "b2":
        case "b3":
        case "c1":
        case "c2":
        case "c3":
        case "d1":
        case "d2":
        case "d3":
            TextIO.putln("This is a valid move!");
            break;
            default:
                TextIO.putln("Not a valid choice, please try again!");
        }
        } while (UserInput!="a2");

However when the choice is valid, it is constantly repeating 'This is a valid move' and vice versa for when it's invalid. Can anyone help with this?

I'll give an example with Scanner(System.in) :

Scanner s = new Scanner(System.in);
String input = "";

do {
    input = s.next();

    switch(input) {
    case "42":
        System.out.println("Success");
        break;
    default:
        System.out.println("Wrong answer!");
    }
} while(!input.equals("42"));

s.next() is a blocking call (in this case), that means program execution is halted while s.next() waits for new user input.

Without that call, the while loop would just keep evaluating the same value of input over and over again, spamming to the console.

It's because the user input has to be set within the loop, so the user is able to type in something else. You're just setting the user input once, iterating over it again and again and again...

You aren't getting another input to be validated before the loop-condition is evaluated each iteration. You need to use a Scanner to gather another input that the loop condition can then validate.

 Scanner scn= new Scanner(System.in);
 do {

    switch (UserInput){
    case "a2":
    case "a3":
    case "b1":
    case "b2":
    case "b3":
    case "c1":
    case "c2":
    case "c3":
    case "d1":
    case "d2":
    case "d3":
        TextIO.putln("This is a valid move!");
        break;
        default:
            TextIO.putln("Not a valid choice, please try again!");
    }

    // We get the new input that we can check for validity
    UserInput = scn.nextLine();
    } while (!UserInput.equals("a2"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM