如何在不消耗 int 本身的情况下从 Scanner 检查 nextInt

How to check nextInt from Scanner without consuming the int itself

我正在尝试做的是验证用户输入的 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();
  }
}

此尝试陷入无限循环。

尽管 Vivin 怎么说,我相信您确实需要 input.next() 电话。如果您无法从 stdin 的下一行读取整数,那么您将陷入无限循环。此外,您应该处理 运行 超出要处理的标准输入行的情况,这可能发生在应用程序的输入来自管道而不是交互式会话的情况下。

在更详细的样式中,这可能类似于:

public static int retrieveYearsBack() throws Exception
{
    Scanner input = new Scanner(System.in);
    while (input.hasNext()) {
        if (input.hasNextInt()) {
            int years = input.nextInt();
            if (0 <= years && years <= 136) {
                return years;
            }
        } else {
            input.next();
        }

        System.out.println("Invalid entry. Please enter a positive whole number less than 136.");
    }

    throw new Exception("Standard in was closed whilst awaiting a valid input from the user.");
}