【问题标题】:Checking if userInput is number with exception检查 userInput 是否是异常的数字
【发布时间】:2017-11-22 19:26:51
【问题描述】:

我正在尝试检查来自用户的输入是否为 int。

到目前为止,这是我的代码:

static int readInt(Scanner userInput) {
    int intValue = 0;

    try {
    System.out.print("Please enter a number:");
    intValue = Integer.parseInt(userInput.nextLine());


    } catch (NumberFormatException ex) {
    Input.readInt(userInput);

    }
    return intValue;
}

问题是:如果我先给它输入不是数字,然后再给它一个数字,它总是返回 0。如果我第一次尝试给它一个数字,它会返回我给它的数字。

我错过了什么? 提前致谢

编辑:我只允许使用 Integer.parseInt 和 Exceptions。

【问题讨论】:

  • 您没有将Input.readInt(userInput); 的返回值分配给您的intValue
  • 考虑将输入代码封装在while-loop 中,以确保程序仅在收到有效输入后继续前进。
  • 如果您只允许使用 Integer.parseInt 和 Exceptions,请编辑您的问题并添加此要求。

标签: java


【解决方案1】:

为避免您的问题,您需要在 catch 块中将此 Input.readInt(userInput) 分配给您的变量。像这样:

intValue  = Input.readInt(userInput);

【讨论】:

    【解决方案2】:

    看起来你没有在 catch 中设置变量

    intValue = Input.readInt(userInput);
    

    【讨论】:

    • 解决了,谢谢!所以我不必输入“Input.readInt(userInput);”完全在我的捕获中,对吧?
    【解决方案3】:

    这里的递归是开销。使用循环:

    Integer result = null;
    do {
        System.out.print("Please enter a number:");
        try {
            result = Integer.parseInt(userInput.nextLine());
        } catch (NumberFormatException ex) {
            System.out.print("Not a number");
        }
    } while(result==null);
    return result;
    

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 2017-05-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 2014-03-21
      • 1970-01-01
      相关资源
      最近更新 更多