0

我阅读了一个菜单选项并输入了除 2 和 5 之外的任何数字。

String choice = promptUser(choicePrompt);
try {
      outputInfo(String.format("choice=...%s...",choice));
      int c = Integer.parseInt(choice);
      /* process it */
}catch (NumberFormatException e) {

outputInfo(String.format("choice=%s",choice));
outputInfo(e.toString());
}

public static void outputInfo(String msg)
{
    System.out.printf("\t%s\n",msg);
}

良好的输出:

    Enter Option: 1
    choice=...1...

错误输出:

    Enter Option: 2
    choice=...2...
    choice=2
    java.lang.NumberFormatException: For input string: ""

更新:

我已经硬编码了“2”,但它仍然失败!:

String choice = promptUser(choicePrompt);
try {
     choice="2";
     outputInfo(String.format("choice=...%s...",choice));
     int c = Integer.parseInt(choice);
     /* process it */
}catch (NumberFormatException e) {

outputInfo(String.format("choice=%s",choice));
outputInfo(e.toString());
}

硬编码“5”也失败,但“1”有效!!!

任何想法都非常感激。

西蒙

4

3 回答 3

1

如果我假设您的promptUser()方法类似于:

static String promptUser() {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    try {
        return reader.readLine();
    }
    catch(Exception ex) {
        return null;
    }
}

(没有参数)然后程序按预期运行 - 当然,该代码中没有任何东西可以区别对待 2 或 5 。如果你得到一个空字符串,那么你确定你的提示用户方法工作正常吗?

无论哪种方式,您在此处发布的代码基本上都是正确的。我想在您更完整的程序中还有其他错误,当您在这里减少它时不会表现出来;例如,也许您遇到了局部变量隐藏字段并且您没有使用您认为的值的情况(但此时,我只是在猜测。)

于 2013-09-19T09:37:05.050 回答
0

更新

似乎 promptUser 方法返回一个空字符串“”。在调用 ParseInt 方法之前检查选项是否为空

您还可以添加 trim() 以消除输入前后的空格

  if(choice!=null && !"".equals(choice))
     int c = Integer.parseInt(choice.trim());
于 2013-09-19T09:35:04.560 回答
0

printStackTrace() 是你的朋友。结果发现数字格式异常进一步下降(在“处理它”代码中)并且没有被捕获。它是数据驱动的,因此不会在其他机器上发生。

感谢每一位的支持。

西蒙

于 2013-09-19T13:38:19.303 回答