我正在尝试从0到43范围生成随机数。但在Some Devices(OnePlus Android 5.0.2和Nexus 5.1)中,它抛出java.lang.IllegalArgumentException:n&lt; = 0:0。我无法捕获该异常以下是我的代码生成随机数。< / p>
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+"");
还有Log
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
答案 0 :(得分:3)
如果nextInt
方法抱怨其参数为0
,则maximum
为0
。这意味着mListofStrings.getMyString().size()
返回1
。尝试从0
包含0
独占生成随机数是没有意义的;这样的int
不存在。但参数值比可返回的最大随机值多一个。这意味着您在分配1
时不应减去maximum
。
int maximum = mListofStrings.getMyString().size();
您可能还想测试size()
方法是否返回0
,并专门处理该案例。
答案 1 :(得分:1)
public static int randInt(int min, int max)
{
Random rand = new Random();
return rand.nextInt((max - min) + 1) + min;
}
将min传递为0,最大值为43(如您所述)并获取范围内的随机数。