In: Computer Science
Create a JAVA lottery game application. Generate four random numbers, each between 0 and 9 (inclusive). Allow the user to guess four numbers. Compare each of the user’s guesses to the four random numbers and display a message that includes the user’s guess, the randomly determined four-digit number, and the amount of points the user has won as follows:
No matches | 0 points |
Any one digit matching | 5 points |
Any two digits matching | 100 points |
Any three digits matching | 2,000 points |
All four digits matching | 1,000,000 points |
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Lottery {
/*
Method to check whether x is present in values array.
*/
public static boolean contains_number(int[] values, int x)
{
for(int num: values)
{
if(num == x)
{
return true;
}
}
return false;
}
public static void main(String[] args)
{
int correct_guesses = 0;
int total_score = 0;
int[] random_nums = new int[4];
int[] guesses = new int[4];
// Asking user to guess four numbers
System.out.println("------------------------------------------");
System.out.println("\t\tLOTTERY GAME\t\t");
System.out.println("------------------------------------------");
System.out.println("Guess the four numbers between 0 and 9: ");
for(int i=0; i<4; i++)
{
Scanner sc = new Scanner(System.in);
guesses[i] = sc.nextInt();
}
ArrayList numbers = new ArrayList();
for(int i=0; i<=9; i++)
{
numbers.add(i);
}
// Shuffling the arraylist containing values to create random numbers
Collections.shuffle(numbers);
// Taking out first 4 numbers randomly
for(int i=0; i<4; i++)
{
int random_num = (int) numbers.get(i);
random_nums[i] = random_num;
// Checking whether one of the guessed number matches with random number.
// if matches, increase the correct guess count
if(contains_number(guesses, random_num))
{
correct_guesses++;
}
}
// Calculating the user score
switch(correct_guesses)
{
case 0:
total_score = 0;
break;
case 1:
total_score = 5;
break;
case 2:
total_score = 100;
break;
case 3:
total_score = 2000;
break;
case 4:
total_score = 1000000;
break;
default:
break;
}
// Dispalying the user guessed and randomly generated numbers
System.out.print("The user guessed numbers are: ");
for(int num: guesses)
{
System.out.print(String.valueOf(num) + " ");
}
System.out.println();
System.out.print("The randomly generated numbers are: ");
for(int num: random_nums)
{
System.out.print(String.valueOf(num) + " ");
}
System.out.println();
// Printing total score of the user
System.out.println("Total score is " + NumberFormat.getIntegerInstance().format(total_score) + " points.");
}
}
OUTPUT