我应该如何处理java中的NumberFormatException?
是否有方法处理我应该如何处理java中的NumberFormatException?,java,calendar,numberformatexception,Java,Calendar,Numberformatexception,是否有方法处理NumberFormatException的编号(顺序)?我使用Doubleoperand[]制作了一个计算器,如下所示,我想写下发生错误的时间。当我输入“2+k”时,应该会出现“操作数[1]的输入错误”的消息。我该怎么做呢?首先,替换该行 System.out.println("operand[] has the wrong input."); System.out.println(e.getMessage()); 使用该行 System.out.println("opera
NumberFormatException
的编号(顺序)?我使用Double
operand[]制作了一个计算器,如下所示,我想写下发生错误的时间。当我输入“2+k”时,应该会出现“操作数[1]的输入错误”的消息。我该怎么做呢?首先,替换该行System.out.println("operand[] has the wrong input.");
System.out.println(e.getMessage());
使用该行System.out.println("operand[] has the wrong input.");
System.out.println(e.getMessage());
现在,当您使用NumberFormatException(String)
构造函数在MyCalculator.calculate()
方法中抛出异常时,可以传递一条消息。它看起来像这样:calculate(String expression)
{
//validate input code
//...
//if operand 0 not valid
throw new NumberFormatException("operand 0 has the wrong input");
//if operand 1 not valid
throw new NumberFormatException("operand 1 has the wrong input");
//rest of calculate method
}
也许您可以定义一个新的异常。例如
CalculatorException
,它可能包含有关计算的更具体信息,例如哪个操作数不正确。或者您甚至可以定义另一个异常,如illegalOperationException
,它可以扩展CalculatorException
。然后您的方法calculate
可以声明为抛出calculaterException
。总之,我们的想法是定义一个新的异常层次结构,以提供与问题领域更相关的信息
然后,您的代码可以是:
try {
System.out.println("result: " + MyCalculator.calculate(expression));
System.out.println();
} catch(CalculatorException e) {
System.out.println(e.getMessage());
}
在将输入传递给计算器之前,可能需要验证输入是否为数字。如果你在SO上搜索类似“检查字符串是否为数字”之类的内容,你会发现很多示例。显然,
calculate()
方法会将操作数转换为双精度?可以单独捕获异常,并用您想要的显式消息重新显示它们。像抛出新的NumberFormatException(String.format(“操作数[%d]的输入错误。”,操作数索引))代码>。然后您可以在这里捕获NumberFormatException
,并打印其消息。就像Paul的回答,但没有亲自验证输入。只需将它们放入一个double
中,然后捕获/重新显示异常。