Search code examples
javagreenfoot

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


I am a beginner in java and my code to generate a random sums throws a strange exception...

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

}

Maybe it's because I've been staring too much at my screen today but I don't know why I'm getting this error.

Thanks in advance!


Solution

  • You only set this.max if n is 1, 2 or 3. If you've not set it to some other value previously, this.max == 0, so getal2 == Math.sqrt(0) == 0.

    You should add a default case to your switch statement to handle all other values of n. It may be appropriate simply to throw an 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");
    }
    

    or you may have a sensible default value to which you can set this.max.