使用以下方法:
public void localsetValue(String UserInput)
{
System.out.println("Enter New Value:");
while (!console.hasNextInt()){
console.next();
System.out.println("Must be a number.");
}
tempInt = console.nextInt();
console.nextLine();
while (tempInt <0) {
System.out.println("Value must be positive.");
tempInt = console.nextInt();
}
SetSpecificValue(UserInput.toLowerCase(), tempInt);
}
第一个 while 循环检查用户输入的 int 是否有效;这工作正常。
第二个 while 循环检查用户输入的数字是否为正数;这也有效,但此时他们可以输入一个字母,它会抛出异常。
对 Java 还是新手,有没有办法结合这两种检查?
最佳答案
只需使用相同的 while
循环就可以了。
在这里,如果用户输入 int
以外的内容或者输入的 int
为负数,我们将继续循环。
int tmpInt = 0;
boolean flag = false;
while ((flag = !console.hasNextInt()) || (tmpInt = console.nextInt()) < 0){
if (flag) {
console.next();
flag = false;
}
System.out.println("Value must be a positive integer !");
}
关于java - 结合 hasNextInt 和值大于/小于 X 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36448723/