扫描仪使用with while循环和switch语句

时间:2017-09-26 18:37:06

标签: java while-loop java.util.scanner

我用Java创建一个简单的控制台应用程序,但我遇到了麻烦。这是我的代码:

boolean isActive = true;
Scanner scanner = new Scanner(System.in);

do {
try {
    int option = scanner.nextInt();

    switch (option) {

        case 1:
            System.out.println("Search By Registration number: " +
                    "\n------------------------------");
            System.out.println("Enter registration number!");
            String regNumber = scanner.nextLine();
            if (regNumber == incorrect) {
                continue; // return to case 1 and ask enter regnumber one more time
            } else {
                // do stuff
            }

            break;

        case 2:
            System.out.println("Exit the search option: ");
            isActive = false;
            break;

        default:
            System.out.println("Your selection was wrong. Try one more time!");
            break;

    }
} catch (InputMismatchException ex) {
    System.out.println("Your selection was wrong. Try one more time!");
}
scanner.nextLine();
} while (isActive);

如果发生错误,我无法返回案例1。因此,如果发生错误,用户必须再次收到关于输入注册号的消息,依此类推。

2 个答案:

答案 0 :(得分:1)

检查注册号

时,您需要使用 equals()
String regNumber = scanner.next();

但即使这样,你的程序也无法正常工作,在此更改 String regNumber = scanner.nextLine()

ggplot2

答案 1 :(得分:0)

您可以在regNumber的输入周围放一个循环,以便在输入不正确时收听输入。

String regNumber = incorrect;
// String is a reference type, therefore equality with another String's value
// must be checked with the equals() method

while(regNumber.equals(incorrect)){

    if (regNumber.equals(correct)) {
        // Do something if input is correct
    }

}

这可能不是您想要的确切解决方案,但请考虑相同的概念并将其应用于您的计划。有关字符串比较的更多信息,另请参阅this。希望这有帮助!