Write a program that generates a random number and asks the user to guess what t
ID: 3621652 • Letter: W
Question
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. You shall also keep a count of the number of guesses that the user makes. When the user correctly guesses the random number, the program should display the number of guesses. Now add another loop to ask the user if he or she wishes to play the guessing game again. If so, the loop should repeat, otherwise it should terminate.So far, this is what my program looks like, any help or suggestions would be greatly appreciated!
// This program generates a random number and askes the user to guess what the number is
import java.util.Scanner;
import java.util.Random;
public class GuessingGame
{
public static void main(String [] args)
{
//Create a scanner object to read from the keyboard
Scanner kb = new Scanner(System.in);
//Create a random object
Random rand = new Random();
//Identifier declarations
int num = rand.nextInt(100) + 1;
int guess = 0;
int count = 0;
int guesses = 0;
do
{
System.out.println("Guess what number I have (1-100)? ");
guess = kb.nextInt();
guesses ++;
if(num > guess) {
System.out.println("Too high, try again.");
} else if(num < guess) {
System.out.println("Too low, try again.");
} else {
System.out.println("You're right, the number is" + num);
System.out.println("You guessed" + guesses + "times");
}
}
while(guess!=num);
}
}
Explanation / Answer
please rate - thanks
you had your > and < reversed
// This program generates a random number and askes the user to guess what the number is
import java.util.Scanner;
import java.util.Random;
public class GuessingGame
{
public static void main(String [] args)
{
//Create a scanner object to read from the keyboard
Scanner kb = new Scanner(System.in);
//Create a random object
Random rand = new Random();
//Identifier declarations
int num;
int guess = 0;
int guesses = 0;
char yorn;
String in;
do
{
num = rand.nextInt(100) + 1;
guesses = 0;
do
{
System.out.println("Guess what number I have (1-100)? ");
guess = kb.nextInt();
guesses ++;
if(guess > num) {
System.out.println("Too high, try again.");
} else if(guess< num) {
System.out.println("Too low, try again.");
} else {
System.out.println("You're right, the number is " + num);
System.out.println("You guessed " + guesses + " times");
}
}
while(guess!=num);
in=kb.nextLine();
System.out.print("Play again(Y/N)? ");
in=kb.nextLine();
yorn=in.charAt(0);
}while(yorn=='Y'||yorn=='y');
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.