In: Computer Science
java beginner level how do i add messages that say win, too high or too low for a lottery number generator guessing game?
//generate lottery numbers int lottery = (int) (Math.random() * 500);
int guess = 0; boolean correct = false;
// prompt user to enter a guess Scanner input = new Scanner(System.in);
System.out.print ("Enter your lottery pick (three digits): ");
int number = input.nextInt();
// keep asking user until user enters a 3-digit number while (guess < 100 || guess > 500) { // keep asking user until user enters a 3-digit number System.out.print("Enter your lottery pick (three digits): ");
guess = input.nextInt(); if (number == lottery) { correct = true; System.out.println("you win"); }
else if (number < lottery) { System.out.println("too low"); } else if (number > lottery) { System.out.println("too high"); }
// add error message if guess is not 3 digit number System.out.println("Error: You didnt entered a 3-digit number. Please re-enter.");
System.out.println (" the lottery number is " + lottery); } } }
Code Screenshot :
Executable Code:
import java.util.Scanner;
public class Main {
//Main Program
public static void main(String args[]) {
Scanner input = new
Scanner(System.in);
int guess = 0;
boolean correct = false;
int min = 100;
int max=500;
int lottery = min +
(int)(Math.random() * ((max - min) + 1));
// prompt user to enter a
guess Scanner input = new Scanner(System.in);
System.out.print ("Enter your
lottery pick (three digits): ");
guess = input.nextInt();
// keep asking user until
user enters a 3-digit number
while (guess < 100 || guess >
500) { // keep asking user until user enters a 3-digit number
System.out.println("Error: You
didnt entered a 3-digit number. Please re-enter.(100-500");
System.out.print("Enter your
lottery pick (three digits): ");
guess = input.nextInt();
}
if (guess == lottery)
{
correct =
true;
System.out.println("you win");
}
else if (guess < lottery)
{
System.out.println("too low");
}
else if (guess > lottery)
{
System.out.println("too high");
}
// add error message if
guess is not 3 digit number
System.out.println ("The lottery number is " + lottery);
}
}
Sample Output :
Please comment below if you have any queries thanks :)