Exception in thread "main" java.lang.ArithmeticException: / by zero

0

Yes, I know it can not be divided by zero. But I want it to show me a JOption, not that the console throw me an error. It is understood? I must make a switch that when the user indicates the number the switch performs the corresponding function. Very basic AND IT WORKS, but when I put 0 in variable n2, it throws me the following error

  

Exception in thread "main" java.lang.ArithmeticException: / by zero

int n1,n2,s,r,m,d,sw1;


        n1=Integer.parseInt(JOptionPane.showInputDialog(" Ingrese el primer número "));
        n2=Integer.parseInt(JOptionPane.showInputDialog(" Ingrese el segundo número "));
        s=n1+n2;
        r=n1-n2;
        m=n1*n2;
        d=n1/n2;

        sw1=Integer.parseInt(JOptionPane.showInputDialog(" 1 SUMA, 2 RESTA, 3 MULTIPLICA Y 4 DIVIDE "));


        switch (sw1) {
        case 1:
                JOptionPane.showMessageDialog(null, " El total es "+s);
            break;

        case 2:
                JOptionPane.showMessageDialog(null, " El total es "+r);
            break;    


        case 3:    
                JOptionPane.showMessageDialog(null, " El total es "+m);

            break;    

        case 4: 

                    if (n2==0) {

                     JOptionPane.showMessageDialog(null, " NO SE PUEDE DIVIDIR ENTRE 0 ");   

            }else{


                     JOptionPane.showMessageDialog(null, " El total es "+d);    

                    }

            break;

           }


}

}

    
asked by Nicolas Otondo 18.10.2018 в 00:25
source

1 answer

0

The error is precisely because you are doing a division by zero

The operation that causes this is:

d=n1/n2;

Consider validating the case in which n2 has a value of 0, like this:

if(n>0){
  d=n1/n2;      
}else{
  d = 0;
  n2 = 0; //* Asigna el valor para que sea mostrado por el JOptionPane.
}
    
answered by 18.10.2018 в 00:29