for a school project I have created a program that prints the number of lottery tickets the user requests. It works fine, but there is one problem: there are duplicate numbers in the arrays. I have been instructed by my professor that I need to make sure there are no duplicates within the first 5 numbers of the array. How can I iterate through the array, check for duplicate numbers, and then replace each duplicate number with a different random number? For example, if the array is {27, 22, 34, 15, 15} then the program should change the duplicate number to {27, 22, 34, 15, 12}. Please help.
import java.util.Random;
import java.util.Scanner;
/**
* SuperLotto program prompts user for number
* of lottery tickets, printing them as requested
*
* @author j
*/
public class SuperLotto {
/**
* This method declares an array numberList
* containing 6 elements
*/
public static void quickPick() {
int numberList[] = new int[6];
//calls the printTicket method for the array
printTicket(numberList);
}
/**
* This method iterates through array to print the elements
*
* @param numberList - this parameter accepts the array
*/
public static void printTicket(int[] numberList) {
Random rnd = new Random();
/* method assigns random numbers to first
* 5 elements in the array and prints them
*/
for (int i = 0; i < 5; i++) {
System.out.print(rnd.nextInt(((27-1) + 1) + 1) + " ");
}
/* method assigns random number to last element
* in array and prints it in special format
*/
for (int i = 0; i < 1; i++) {
System.out.print("(MEGA: " + rnd.nextInt(((27-1) + 1) + 1) + ")");
}
}
//main method
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String name;
int numberOfTickets;
String decide;
//Program prompts the user for their name
System.out.println("Welcome to the Quicky Mart, what is your name?");
//User inputs their name
name = scnr.next();
//new line
System.out.println();
//Program prompts the user for number of tickets
System.out.println("Hi " + name + ", how many Super Lotto "
+ "tickets would you like to purchase?");
//User inputs the number of tickets
numberOfTickets = scnr.nextInt();
//new line
System.out.println();
/* Program outputs the number
* of tickets entered by user
*/
System.out.println("Super Lotto Ticket(s): ");
for (int i = 0; i < numberOfTickets; i++) {
quickPick();
System.out.println();
}
//new line
System.out.println();
/* System prompts user if they would
* like to run the program again
*/
System.out.println("Good luck! "
+ "Would you like to run the program again?");
//User enters their decision
decide = scnr.next();
/* If user decides yes,
* main program runs again
*/
while (decide.equalsIgnoreCase("yes")) {
System.out.println();
main(null);
break;
}
/* If user decides no,
* program terminates with a message
*/
if (decide.equalsIgnoreCase("no")) {
System.out.println();
System.out.println("Goodbye!");
}
}
}