Hi how do i avoid getting a duplicate "lottery ticket" in my code?
The problem now is everything works fine, the sorting , the randoming numbers , the making it into a String. The problem is that if i for example want 5 lottery tickets than it i will print out 5 lottery tickets
Example
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]
As you can see there is duplicate numbers, i want to avoid this so it will always random. How do i avoid this?
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;
}
}
getTicketmethod, you can implement a loop to keep generating random numbers until there are no duplicates.