Arithmetic Exception divide by zero : but i am already restricting it not to produce zero

152 Views Asked by At

here is my sample code, logcat is showing exception in while statement, I am out of mind now. I don't know how and why it is being divided by zero. Help me please :

public void divisionQuestion() {
    int a;
    int b;
    Random random = new Random();
    do {
        a = random.nextInt(40);
        b = random.nextInt(20);
    } while (a % b != 0 || a < 3 || b < 2);
}

My logcat :

java.lang.IllegalStateException: Could not execute method for android:onClick
    at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
    at android.view.View.performClick(View.java:6256)
    at android.view.View$PerformClick.run(View.java:24701)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
    at android.view.View.performClick(View.java:6256) 
    at android.view.View$PerformClick.run(View.java:24701) 
    at android.os.Handler.handleCallback(Handler.java:789) 
    at android.os.Handler.dispatchMessage(Handler.java:98) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6541) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
 Caused by: java.lang.ArithmeticException: divide by zero
    at com.universeCoding.mathtestapp.QuestionAnswerAdapter.divisionQuestion(Adapter.java:228)
2

There are 2 best solutions below

0
On

This statement:

a % b != 0

will give an error when b is zero.

The problem is that it can be zero, since this line:

b = random.nextInt(20);

will allow b to be any random value in the range [0, 20[.

1
On

you can avoid from this problem by

adding "if(b!=0)" statement