java.lang.IllegalArgumentException: n must be positive


public static String  randomKey(){
		Random random = new Random();
		int key = random.nextInt(((int)System.currentTimeMillis()));
		return String.valueOf(key);
	}

  直接調用方法,發生異常:

Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
    at java.util.Random.nextInt(Random.java:300)
    at com.stresstest.example.RandomTest.randomKey(RandomTest.java:24)
    at com.stresstest.example.RandomTest.main(RandomTest.java:15)

異常說明:

java.lang.IllegalArgumentException: n must be positive
參數異常,n必須是一個整數,顯然(int)System.currentTimeMillis()產生的值不是一個正數。

分析:
  系統產生的異常,測試時系統正常,上線之后某一天之后產生了異常。
查看System.currentTimeMillis()產生了問題,產生異常時間是2015-05-23當天開始往后,一直報錯。之前就沒事

時間:2015-05-23
測試結果:正常
System.currentTimeMillis():1432350368523
(int)System.currentTimeMillis():2126349176
randomKey():1369912950
時間:2015-05-24
測試結果:
1432436706512
-2082194224 Exception in thread "main" java.lang.IllegalArgumentException: n must be positive at java.util.Random.nextInt(Random.java:300) at com.stresstest.example.RandomTest.randomKey(RandomTest.java:24) at com.stresstest.example.RandomTest.main(RandomTest.java:15)
 
        

  因此可以知道結果,陰性問題,值得注意,至於long型轉換為int型出現問題在這里不做深究,有這個問題深層研究的請補充。

解決辦法:

int key = random.nextInt(((int)System.currentTimeMillis()));
修改為:
  1.random.nextInt(((int)System.currentTimeMillis()/1000));
  2.random.nextInt(999999999);
 





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM