Java scanner input validation [duplicate]

。_饼干妹妹 提交于 2021-01-28 09:57:14

问题


I am trying to accept only three numbers from my input: 1, 2, 3. Any other different than that must be invalid. I have created method but I don't have an idea why it did not working. What must I change?

int number;
do {
    System.out.println("Enter 1, 2 or 3");
    while (!scanner.hasNextInt()) {
        System.out.println("Invalid input!");
    }
    number = scanner.nextInt();
} while (number == 1 || number == 2 || number == 3)
return number;

回答1:


Your loop logic

do {
    ...
} while (number == 1 || number == 2 || number == 3);

requires staying in the loop for as long as the answer is valid. You want to invert your condition:

do {
    ...
} while (!(number == 1 || number == 2 || number == 3));

or use De Morgan's Law to invert individual components:

do {
    ...
} while (number != 1 && number != 2 && number != 3);

In addition, when Scanner's hasNextInt returns false, you need to take the invalid input off the scanner, for example with nextLine that you ignore. Otherwise you get an infinite loop:

while (!scanner.hasNextInt()) {
    System.out.println("Invalid input!");
    scanner.nextLine(); // This input is ignored
}


来源:https://stackoverflow.com/questions/47849658/java-scanner-input-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!