Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Random Number llegalArgumentException: n <= 0: 0

I am trying to generate Random Number from 0 to 43 range. But at Some Devices (OnePlus Android 5.0.2 and Nexus 5.1) it is throwing java.lang.IllegalArgumentException: n <= 0: 0. I am not able to catch that exception Below is my Code to generate the random Number.

    Random rand = new Random();
    int maximum = mListofStrings.getMyString().size() - 1;
    Log.e("Max",""+maximum);
    Mint.logEvent("Maximum", MintLogLevel.Error);
    int randomNum;
    try{

       // randomNum = rand.nextInt(43);
        randomNum = rand.nextInt(maximum);
    }catch (IllegalArgumentException e){
        e.printStackTrace();
        randomNum = 8;
    }

    Log.e("random number", randomNum+"");

And also Log is

1   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
2   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
3   at android.app.ActivityThread.access$900(ActivityThread.java:147)
4   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
5   at android.os.Handler.dispatchMessage(Handler.java:102)
6   at android.os.Looper.loop(Looper.java:135)
7   at android.app.ActivityThread.main(ActivityThread.java:5254)
8   at java.lang.reflect.Method.invoke(Native Method)
9   at java.lang.reflect.Method.invoke(Method.java:372)
10  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
11  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
12Caused by: java.lang.IllegalArgumentException: n <= 0: 0
13  at java.util.Random.nextInt(Random.java:182)
14  at com.algo.toiletbreak.ShareActivity.onCreate(Unknown Source)
15  at android.app.Activity.performCreate(Activity.java:5933)
16  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
17  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
18  ... 10 more
like image 602
Malik Umar Avatar asked Sep 27 '22 23:09

Malik Umar


1 Answers

If the nextInt method is complaining that its argument was 0, then maximum was 0. That implies that mListofStrings.getMyString().size() returned 1. There's no point in attempting to generating a random number from 0 inclusive through 0 exclusive; such an int doesn't exist. But the parameter value is one more than the maximum random value that can be returned. This means that you should not subtract 1 when assigning maximum.

int maximum = mListofStrings.getMyString().size();

You may also want to test if the size() method returns 0, and handle that case specially.

like image 129
rgettman Avatar answered Oct 06 '22 02:10

rgettman