我正在尝试这个小小的计算器程序。当我调用calculateResult()方法时,我想在secondOperand为零且运算符为除法时显示IllegalStateException错误。但即使如此,我在calculateResult()中放了一个if子句来显示这个错误,我没有得到错误,但是我得到了无穷大。我应该如何更改我的代码以显示此错误?以下是我的代码。
public double calculateResult() {
if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '+') {
return firstOperand + secondOperand;
}
else if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '-') {
return firstOperand - secondOperand;
}
else if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '*') {
return firstOperand * secondOperand;
}
else if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '/') {
return firstOperand / secondOperand;
}
else if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '%') {
return firstOperand % secondOperand;
}
else if (secondOperand == '0' || operator == '/'){
throw new IllegalStateException ("Cannot divided by zero"); //this error never comes up when I print out calcualteResult() method.
}else {
return Double.NaN;
}
}
public static void main(String[] args) {
// main method
Calculator first = new Calculator();
first.setFirstOperand(5.0);
first.setSecondOperand(0);
first.setOperator('/');
first.calculateResult(); // I get [5.0 / 0.0 = Infinity] here...
System.out.println(first);
答案 0 :(得分:2)
你还没有发布有问题的实际代码,所以我不能肯定地说,但是零检测有两个问题。首先,您要比较的是Double
或double
与char
的值'0'
,而不是0
。删除数值周围的单引号。此外,在评估操作之前,需要检查无效输入!如果operator
为'/'
(或'%'
),则需要在分割前检查零。
这段代码是一个严重的混乱,而且它很简单,如果你必须使用operator
的字符,我将展示它应该如何编写(类似枚举的东西几乎总是更好的选择)。
public double calculateResult() {
// check in one place instead of duplicating
if(Double.isNaN(first) || Double.isNaN(second))
return Double.NaN;
// check preconditions *before* calculating
if(second == 0.0 && (operator == '/' || operator == '%'))
throw new IllegalStateException("explanation");
switch(operator) {
case '+': return first + second;
case '-': return first - second;
case '*': return first * second;
case '/': return first / second;
case '%': return first % second;
default: return new IllegalStateException("unsupported operation");
}
}
答案 1 :(得分:1)
如果secondOperand
为零且operator
为'/',则会先通过检查,执行计算并返回正确计算的infinity
值:
else if (firstOperand != Double.NaN && secondOperand != Double.NaN && operator == '/') {
return firstOperand / secondOperand;
}
正如其他答案和评论中所指出的,您的某些代码(包括此代码段)在其他方面是错误的。
您应该使用Double.isNan(operand)
来测试某些内容是否为NaN
,因为NaN
相等规则有点奇怪。最后,你不想检查双重和一个字符是否相等。
但是如果你想特别处理除零,你需要在之前检查它它还遇到的其他条件。
答案 2 :(得分:0)
else if (secondOperand == 0 && operator == '/'){ ... }
您正在尝试将double值与char('0')
进行比较