Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我应该如何处理java中的NumberFormatException?_Java_Calendar_Numberformatexception - Fatal编程技术网

我应该如何处理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
中,然后捕获/重新显示异常。