Question Practice on Random Number and Loops
Q.Write a program that generates a random number and asks the user to
guess what the number is. If the user's guess is higher than the random
number, the program should display "Too high, try again." If the
user's guess is lower than the random number, the program should display
"Too low, try again." The program should use a loop that repeats
until the user correctly guesses the random number.
SOLUTION
import java.util.Random;
import java.util.Scanner;
public class orange {
public static void main(String[] args) {
Random bucky = new Random();
Scanner bucky1 = new Scanner(System.in);
int number, guess;
number = bucky.nextInt(6);
System.out.println("Your Guess?");
guess = bucky1.nextInt();
while (number != guess) {
if (number < guess) {
System.out.println("Too High, Try Again");
guess = bucky1.nextInt();
} else if(number > guess) {
System.out.println("Too Low, Try Again");
guess = bucky1.nextInt();
}
if (number == guess) {
System.out.println("Congratulations!");
}
Comments
Post a Comment