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

时间:2015-03-12 21:10:25

标签: java conditional java.util.scanner

我试图做的是验证用户输入0到13之间的整数,同时还要确保输入IS实际上是一个整数。我无法找到一个好方法,因为在条件中使用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();
  }
}

此尝试陷入无限循环。

1 个答案:

答案 0 :(得分:-2)

尽管Vivin说的话,我相信你确实需要input.next()电话。如果你不能从stdin的下一行读取一个整数,那么你将进入无限循环。此外,您应该处理用尽要处理的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.");
}