Program Description: Write a program called GuessingGame.java with a main method
ID: 3762224 • Letter: P
Question
Program Description: Write a program called GuessingGame.java with a main method that generates a random number between 1 and 100, then allows the user 10 attempts to guess the number. Each time he or she makes a guess your program should output whether the guess was too high or too low or just right. If the user has guessed the number, the program should call the method winner then end. If the user runs out of guesses the program should call the method loser then end.
winner method- tells the user he won, and how many guesses it took him to guess the number.
loser method- tells the user he lost, and what the number actually was.
Sample output:
Welcome to the number guessing game where you will guess a number between 1 and 100.
What is your guess?
83 Too high!
What is your guess?
22 Too low!
What is your guess?
59 Too high!
What is your guess?
53 You guessed my number is 4 guesses!
Thanks for playing the number guessing game!
Explanation / Answer
import java.util.Random;
import java.util.Scanner;
public final class GuessingGame {
public static void main(String[] args) {
Random r = new Random();
Scanner sc = new Scanner(System.in);
int randomNumber = r.nextInt(100) + 1;
int numTurns=10;
System.out.println("Welcome to the number guessing game where you will guess a number between 1 and 100.");
while (numTurns != 0) {
System.out.println("What is your guess?");
int ans = sc.nextInt();
if (ans > randomNumber) {
System.out.println("Too High!");
} else if (ans < randomNumber) {
System.out.println("Too Low!");
} else {
System.out.println("You guessed my number is "+(10-numTurns+1)+" guesses!");
System.out.println("Thanks for playing the number guessing game!");
return;
}
numTurns--;
}
System.out.println("Sorry.. You lost the game!");
System.out.println("Thanks for playing the number guessing game!");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.