您應該首先創建一個Random
的實例。這會爲你生成隨機數字。然後,您應該將所有已經生成的號碼保存在ArrayList<Integer>
中,以便您可以跟蹤迄今爲止生成的號碼。
Random mRandom=new Random();
//Generate first number, int [0,20)
int no=mRandom.nextInt(20);
//keep that number
ArrayList<Integer> mGeneratedSoFar=new ArrayList<Integer>();
mGeneratedSoFar.add(no);
然後在點擊按鈕的處理程序,產生了到現在爲止生成的數字:
int no=mRandom.nextInt(20);
while(mGeneratedSoFar.contains(no)){
no=mRandmom.nextInt(20);
}
mGeneratedSoFar.add(no);
編輯:和@Guido加西亞說,你可以保持你的號碼在其它類型Collection
或Maps
獲得更好的性能。但只要你產生少量的數字,我不認爲這會是一個問題。
有什麼問題嗎? –
你能展示一些代碼嗎? – Oyeme