我阅读了一个菜单选项并输入了除 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”有效!!!
任何想法都非常感激。
西蒙