我有这个代码用于生成随机数...
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
我正在使用它......
List<Integer> sounds = new ArrayList<Integer>();
public int getSound() {
return sounds.get(InGameActivity.randInt(0, sounds.size() - 1));
}
我收到此错误:
01-11 00:46:31.500: E/AndroidRuntime(1105): FATAL EXCEPTION: main
01-11 00:46:31.500: E/AndroidRuntime(1105): java.lang.IllegalArgumentException: n <= 0: 0
01-11 00:46:31.500: E/AndroidRuntime(1105): at java.util.Random.nextInt(Random.java:175)
01-11 00:46:31.500: E/AndroidRuntime(1105): at com.example.chess.InGameActivity.randInt(InGameActivity.java:2119)
01-11 00:46:31.500: E/AndroidRuntime(1105): at com.example.chess.ChessPiece.getSound(ChessPiece.java:171)
01-11 00:46:31.500: E/AndroidRuntime(1105): at com.example.chess.InGameActivity$MyOnClickListener.onClick(InGameActivity.java:389)
01-11 00:46:31.500: E/AndroidRuntime(1105): at android.view.View.performClick(View.java:4240)
01-11 00:46:31.500: E/AndroidRuntime(1105): at android.view.View$PerformClick.run(View.java:17721)
01-11 00:46:31.500: E/AndroidRuntime(1105): at android.os.Handler.handleCallback(Handler.java:730)
01-11 00:46:31.500: E/AndroidRuntime(1105): at android.os.Handler.dispatchMessage(Handler.java:92)
01-11 00:46:31.500: E/AndroidRuntime(1105): at android.os.Looper.loop(Looper.java:137)
01-11 00:46:31.500: E/AndroidRuntime(1105): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-11 00:46:31.500: E/AndroidRuntime(1105): at java.lang.reflect.Method.invokeNative(Native Method)
01-11 00:46:31.500: E/AndroidRuntime(1105): at java.lang.reflect.Method.invoke(Method.java:525)
01-11 00:46:31.500: E/AndroidRuntime(1105): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-11 00:46:31.500: E/AndroidRuntime(1105): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-11 00:46:31.500: E/AndroidRuntime(1105): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:3)
因为在你的情况下
(max - min) + 1
不到一个
01-11 00:46:31.500:E / AndroidRuntime(1105):java.lang.IllegalArgumentException:n&lt; = 0:0