Home > OS >  Can't divide by zero exception
Can't divide by zero exception

Time:10-26

I know my error is a common one, but I do have an if condition to catch this error. I'm working with android studio. The language I'm using is kotlin.

I want to calculate this formula: A = ((2varX) varF) / (varX-(2varF)).

There are two main problems, one is that X and F are 0, I have an if statement for this. The second issue would be if F is half of X, this would give me 0 in my denominator.

Since I'm working with android studio I have two input boxes where the user inputs the variables. I have already validated that the user inputs only numbers and that the camps are not left empty. I have no issue here. My problem is when I input 2 and 1. This would cause my denominator to be 0. When this happens, I get an error and my app shuts down.

var auxiliar = varF/2
if (varX != 0 && varF != 0 && auxiliar != varX) {
    var resultado = ((2*varX) varF) / (varX-(2*varF))
    resultadoFormula.setText("a = ${resultado}")
} else {
    message("Combinacion Incorrecta")
}

This is my code. I would appreciate the help.

I get this error. E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.eval_2_data, PID: 8657 java.lang.ArithmeticException: divide by zero

CodePudding user response:

You need to make sure varX != 2*varF, because if it does the denominator is 0. ((2*varX) varF) / (varX-(2*varF)) will have 2-2*1 in the denominator, which is 0 because of pemdas. Whenever there is division by 0, this will cause an exception to get thrown.

CodePudding user response:

A try catch block will stop the fatal error and allow the app to continue running.

var auxiliar = varF/2

try {
     if (varX != 0 && varF != 0 && auxiliar != varX) {
     var resultado = ((2*varX) varF) / (varX-(2*varF))
     resultadoFormula.setText("a = ${resultado}")
} else {
     message("Combinacion Incorrecta")
     }
} catch (ArithmeticException e) {
     System.out.println("I didn't do my math correctly.")
}
  • Related