2014-01-11 117 views
0

當一個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) 
+0

確保sounds.size的值()> 0 –

回答

3

,因爲你的情況

(max - min) + 1 

去不到一個

01-11 00:46:31.500: E/AndroidRuntime(1105): java.lang.IllegalArgumentException: n <= 0: 0

+0

實際上,它不能小於零。它是ZERO –

+2

_goes小於one_ –