我是java初学者,我生成随机和的代码抛出了一个奇怪的异常......
public void randomRekensom(int n)
{
switch(n) {
case 1: this.max = 100;
break;
case 2: this.max = 150;
break;
case 3: this.max = 200;
break;
}
getal1= (int) Math.sqrt(max);
getal2= (int) Math.sqrt(max);
operator=ThreadLocalRandom.current().nextInt(1, 4 + 1);
switch(operator) {
case 1: antwoord=(this.getal1+this.getal2);
operatorTeken=" + ";
break;
case 2: antwoord=(this.getal1-this.getal2);
operatorTeken=" - ";
break;
case 3: antwoord=(this.getal1/this.getal2);
operatorTeken=" / ";
break;
case 4: antwoord=(this.getal1*this.getal2);
operatorTeken=" * ";
break;
}
}
也许是因为我今天盯着屏幕看太多了,但我不知道为什么会收到此错误。
提前致谢!
最佳答案
您只设置this.max
如果n
是 1、2 或 3。如果您之前没有将其设置为其他值,this.max == 0
,所以getal2 == Math.sqrt(0) == 0
.
您应该添加 default
案例给您switch
处理 n
的所有其他值的语句。简单地抛出 IllegalArgumentException
可能是合适的。 .
switch(n) {
case 1: this.max = 100;
break;
case 2: this.max = 150;
break;
case 3: this.max = 200;
break;
default: throw new IllegalArgumentException("Not 1, 2 or 3");
}
或者您可能有一个合理的默认值,您可以将其设置为 this.max
.
关于java - 为什么我收到 java.lang.ArithmeticException :/by zero?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36295950/