gpt4 book ai didi

java - IllegalStateException 未按需要显示

转载 作者:行者123 更新时间:2023-12-01 23:15:13 27 4
gpt4 key购买 nike

我正在尝试这个小计算器程序。当我调用calculateResult()方法时,我想在第二个操作数为零且运算符为除法时显示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);

最佳答案

您还没有发布有问题的实际代码,所以我不能肯定地说,但是零检测具体有两个问题。首先,您将 Doubledouble 与值为 '0'char 进行比较,而不是0。删除数值两边的单引号。此外,在评估操作之前,需要检查无效输入!如果运算符'/'(或'%'),则需要在除法之前检查零。

这段代码一团糟,而且很简单,如果您必须使用字符作为运算符,我将展示应该如何编写它(像枚举这样的东西几乎总是更好的选择)选择)。

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");
}
}

关于java - IllegalStateException 未按需要显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21345810/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com