-2

这是我的示例代码,logcat 在 while 语句中显示异常,我现在疯了。我不知道它如何以及为什么被零除。请帮帮我 :

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

我的日志猫:

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)
4

2 回答 2

0

这个说法:

a % b != 0

b为零时会出错。

问题是它可以为零,因为这条线:

b = random.nextInt(20);

将允许b是范围内的任何随机值[0, 20[

于 2019-12-01T13:20:01.730 回答
0

您可以通过以下方式避免此问题

添加“if(b!=0)”语句

于 2019-12-01T13:23:46.210 回答