【发布时间】:2015-05-15 05:28:28
【问题描述】:
我正在尝试做的是验证用户输入的 0-136 之间的整数,同时还要确保输入实际上是整数。我想不出这样做的好方法,因为在条件中使用 nextInt 会消耗 int,并且您无法将 hasNextInt 与整数进行比较。任何帮助将不胜感激!
这是我的代码:
public static int retrieveYearsBack() {
Scanner input = new Scanner(System.in);
//Retrieve yearsBack
System.out.println("How many years back would you like to search? (Enter only positive whole numbers less than 136)");
while (!input.hasNextInt([0-136]) {
System.out.println("Invalid entry. Please enter a positive whole number less than 136 only.");
input.next();
}
return input.nextInt();
}
我也试过了:
int myYears = -1;
int tempValue = 0;
while (!input.hasNextInt() || (myYears < 0 || myYears > 136)) {
if (input.hasNextInt())
tempValue = input.nextInt();
if (tempValue > 0 && tempValue < 136)
myYears = tempValue;
else {
System.out.println("Invalid entry. Please enter a positive whole number less than 136 only.");
input.next();
}
}
此尝试陷入无限循环。
【问题讨论】:
-
This 可能会有所帮助。
标签: java conditional java.util.scanner