嗨我如何避免在我的代碼中獲取重複的「彩票」?我如何避免在我的Int數組中獲取相同的數字?
現在的問題是一切工作正常,排序,隨機數字,使其成爲一個字符串。 的問題是,如果我例如想要5張彩票比我會打印出5張彩票
例
Lottery tickets:
--------------
[5, 13, 18, 22, 23, 23, 30]
[4, 7, 10, 12, 16, 26, 32]
[3, 5, 9, 22, 23, 25, 34]
[4, 5, 15, 18, 19, 19, 26]
[3, 3, 12, 14, 23, 26, 35] (Duplicate 3)
[5, 6, 12, 13, 14, 15, 26]
正如你可以看到有重複號碼,我想這樣就可以避免這一點,將始終是隨機的。我如何避免這種情況?
import java.util.Arrays;
import java.util.Scanner;
public class Alt2 {
public static void main(String[] args) {
System.out.print("How many lottery tickets do u want?: \n");
Scanner svar= new Scanner(System.in);
int nr = svar.nextInt();
System.out.println("Lottery tickets: ");
System.out.println("--------------");
for(int i=0; i<nr; i++)
{
Alt2 t = new Alt2();
int[] lottoNummer = t.BubbleSort();
System.out.print(Arrays.toString(lottoNummer));
System.out.println();
svar.close();
}
}
private int[] getTicket(){
int[] lottoNummer = new int[7];
lottoNummer[0] = (int) ((35 * Math.random()) + 1);
lottoNummer[1] = (int) ((35 * Math.random()) + 1);
lottoNummer[2] = (int) ((35 * Math.random()) + 1);
lottoNummer[3] = (int) ((35 * Math.random()) + 1);
lottoNummer[4] = (int) ((35 * Math.random()) + 1);
lottoNummer[5] = (int) ((35 * Math.random()) + 1);
lottoNummer[6] = (int) ((35 * Math.random()) + 1);
return lottoNummer;
}
public int[] BubbleSort()
{
int j;
boolean flag = true;
int temp;
Alt2 t = new Alt2();
int[] lottoNummer = t.getTicket();
while (flag)
{
flag= false;
for(j=0; j < lottoNummer.length -1; j++)
{
if (lottoNummer[ j ] > lottoNummer[j+1])
{
temp = lottoNummer[ j ];
lottoNummer[ j ] = lottoNummer[ j+1 ];
lottoNummer[ j+1 ] = temp;
flag = true;
}
}
}
return lottoNummer;
}
}
在你的'getTicket'方法,你可以實現一個循環,以保持生成隨機數,直到有沒有重複。 – 2015-02-06 15:49:17
http://stackoverflow.com/questions/28095667/fill-an-array-with-unique-random-numbers – assylias 2015-02-06 15:50:08