java - Android Random Number llegalArgumentException: n <= 0: 0 -
i trying generate random number 0 43 range. @ devices (oneplus android 5.0.2 , nexus 5.1) throwing java.lang.illegalargumentexception: n <= 0: 0. not able catch exception below code generate 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 log
1 @ android.app.activitythread.performlaunchactivity(activitythread.java:2329) 2 @ android.app.activitythread.handlelaunchactivity(activitythread.java:2389) 3 @ android.app.activitythread.access$900(activitythread.java:147) 4 @ android.app.activitythread$h.handlemessage(activitythread.java:1296) 5 @ android.os.handler.dispatchmessage(handler.java:102) 6 @ android.os.looper.loop(looper.java:135) 7 @ android.app.activitythread.main(activitythread.java:5254) 8 @ java.lang.reflect.method.invoke(native method) 9 @ java.lang.reflect.method.invoke(method.java:372) 10 @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:898) 11 @ com.android.internal.os.zygoteinit.main(zygoteinit.java:693) 12caused by: java.lang.illegalargumentexception: n <= 0: 0 13 @ java.util.random.nextint(random.java:182) 14 @ com.algo.toiletbreak.shareactivity.oncreate(unknown source) 15 @ android.app.activity.performcreate(activity.java:5933) 16 @ android.app.instrumentation.callactivityoncreate(instrumentation.java:1105) 17 @ android.app.activitythread.performlaunchactivity(activitythread.java:2282) 18 ... 10 more
if nextint
method complaining argument 0
, maximum
0
. implies mlistofstrings.getmystring().size()
returned 1
. there's no point in attempting generating random number 0
inclusive through 0
exclusive; such int
doesn't exist. parameter value 1 more maximum random value can returned. means should not subtract 1
when assigning maximum
.
int maximum = mlistofstrings.getmystring().size();
you may want test if size()
method returns 0
, , handle case specially.
Comments
Post a Comment