當一個IllegalArgumentException我有產生隨機數的代碼...獲取生成隨機數
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)
確保sounds.size的值()> 0 –