In: Computer Science
Respond to the following in a minimum of 175 words:
As the question requires, we need to use the arrays for the lottery system. then for obtaining the lottery number, we are to use the Random class to generate the random/lottery number. This program requires the use of various methods, for example, to check whether a ticket is available or not, or to check if the user wor or not. The working code for this question is:
import java.io.PrintStream;
import java.util.*;
public class Test {
private static int[] ticketNumber;
private static int[] usersTickets;
public static void main(String[] args) {
ticketNumber = new int[100];
for(int i=0; i<100; i++){
ticketNumber[i] = i+1;
}
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Lottery game.\n---------------------------------------------------------");
System.out.println("How many tickets would you like to draw: ");
int n = sc.nextInt();
usersTickets = new int[n];
int i=0;
while (i < n) {
System.out.println("Enter number for ticket " + (i+1)+ ": ");
int num = sc.nextInt();
if (num <= ticketNumber.length) {
if (isAvailable(ticketNumber, num)) {
ticketNumber = removeFromArray(ticketNumber, num);
System.out.println("good you have taken ticket numbered "+num);
usersTickets[i] = num;
i++;
}
else
System.out.println("Ticket number not available!");
}
else {
System.out.println("This much tickets not available. Enter a smaller number: ");
}
}
System.out.println("Getting the lottery draw........................");
int luckyNo = luckyNumber();
System.out.println("The lucky number is "+luckyNo);
int result = didYouWin(usersTickets, luckyNo);
if(result != 0)
System.out.println("Congratulations!!! Yoy won the lottery on ticket "+luckyNo);
else
System.out.println("Better luck next time!!!!");
}
public static int didYouWin(int[] yourTickets, int luckyNo){
for(int i = 0; i<yourTickets.length; i++){
if(yourTickets[i]==luckyNo){
return i;
}
}
return 0;
}
public static int luckyNumber () {
Random rand = new Random();
return rand.nextInt(100) + 1;
}
public static boolean isAvailable ( int[] arr, int num){
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num)
return true;
}
return false;
}
public static int[] removeFromArray ( int[] arr, int num){
int[] newArray = new int[arr.length - 1];
for( int i=0, k=0; i<newArray.length; i++){
if(arr[i] == num){
continue;
}
newArray[k++] = arr[i];
}
return newArray;
}
}