0
我想验证1或2的输入。但是,使用此代码,如果您输入字母,它会使程序崩溃。isDigit validation
这怎么解决?
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();
}
}
使用尝试,赶上这样,它不会破坏程序。你应该看看它在java中非常有用的文档,你可以尝试/捕获一切:D –