【发布时间】:2018-02-25 23:01:07
【问题描述】:
因此,如果用户输入像 453-* 这样的后缀值,我的方法 EvalPostFix() 会起作用,但是当用户输入像 43*+ 这样的无效字符串或任何无效字符串时,程序希望程序重新提示用户输入不知道如何用 try catch 实现..
'
String in;
while(true){
System.out.println("Please enter the numbers first followed by the operators, make sure to have one less operator than of numbers");
try {
in = getString();
int result = EvalPostFix(in);
System.out.println(result);
} catch (IOException e) {
// TODO Auto-generated catch block
String s = "Not a valid postfix string";
e.toString();
in = getString();
}
}
'
【问题讨论】:
-
您应该避免对用户输入/输出使用异常。而是创建一个返回(布尔)结果或类似结果的验证函数。此外,抛出 IOException 并不是一个好主意,它可能是一个解析异常或类似的异常。并且永远不要使用没有
break的while(true)循环:) -
@owlstead 仍然应该捕获用户输入,这些输入无法解析为预期的格式,这最容易通过异常处理来完成
-
嗯,是的,在这种情况下,您可以对输入进行简单的检查并处理我猜想的解析器异常,为其重新创建另一个解析器是多余的。
标签: java