为什么我得到 java.lang.ArithmeticException: / 为零?

Why am I getting java.lang.ArithmeticException: / by zero?

我是 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;
}

}

可能是因为我今天一直盯着屏幕看,但我不知道为什么会出现此错误。

提前致谢!

如果 n 是 1、2 或 3,您只设置 this.max。如果您之前没有将其设置为其他值,this.max == 0,那么 getal2 == Math.sqrt(0) == 0.

您应该在 switch 语句中添加一个 default 案例来处理 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