我正在尝试验证输入1或2.但是,使用此代码,如果输入字母,则会导致程序崩溃。
如何解决这个问题?
System.out.print("Choice: ");
userSelection = keyboard.nextInt();
while (flag == 0)
{
if (userSelection == 1 || userSelection == 2)
{
flag = 1;
}
if(Character.isDigit(userSelection))
{
flag = 1;
}
else
{
flag = 0;
}
if (flag == 0)
{
//this is a system clear screen to clear the console
System.out.print("\033[H\033[2J");
System.out.flush();
//display a warning messege that the input was invalid
System.out.println("Invalid Input! Try again, and please type in selection 1 or selection 2 then hit enter");
System.out.print("Choice: ");
userSelection = keyboard.nextInt();
}
}
答案 0 :(得分:1)
nextInt
期望用户键入一个整数。否则就会失败。
您可能想要使用nextLine
构建一些内容(它会读取您可以检查的输入行,reading single characters as they are being typed is tricky in Java)。
答案 1 :(得分:0)
试试这段代码:
try (Scanner scanner = new Scanner(System.in)) {
int choice;
while (true) {
System.out.print("Choice: ");
if (!scanner.hasNextInt()) {
scanner.nextLine();//read new line character
System.err.println("Not a number !");
continue; // read again
}
choice = scanner.nextInt(); //got numeric value
if (1 != choice && 2 != choice) {
System.err.println("Invalid choice! Type 1 or 2 and press ENTER key.");
continue; //read again
}
break;//got desired value
}
System.out.printf("User Choice: %d%n", choice);
}