简体   繁体   English

做while循环错误(switch语句)

[英]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.我是 java 的初学者,并试图在 switch 语句中为许多情况实现 do while 循环。

    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. 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(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. s.next()是一个阻塞调用(在这种情况下),这意味着在s.next()等待新的用户输入时程序执行被暂停。

Without that call, the while loop would just keep evaluating the same value of input over and over again, spamming to the console.如果没有那个调用,while 循环只会一遍又一遍地评估相同的input值,向控制台发送垃圾邮件。

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 来收集循环条件可以验证的另一个输入。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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