【问题标题】:How to check nextInt from Scanner without consuming the int itself如何在不消耗 int 本身的情况下从 Scanner 检查 nextInt
【发布时间】: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


【解决方案1】:

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

在更详细的样式中,这可能看起来像:

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.");
}

【讨论】:

  • 你说得对,汤姆——我已经删除了对 input.close() 的调用。我之前认为它可以整理 Scanner,而不是它使用的底层流。
猜你喜欢
  • 1970-01-01
  • 2022-11-05
  • 2019-10-04
  • 2022-01-14
  • 1970-01-01
  • 2015-12-26
  • 2020-09-02
  • 2016-04-18
  • 1970-01-01
相关资源
最近更新 更多