Answer:
import java.util.Scanner;
import java.util.Random;
public class Guesser {
// Create a scanner object to read from the keyboard
static Scanner kb = new Scanner(System.in);
// Create a random object
static Random rand = new Random();
public static void main(String[] args) {
playGame();
}
public static void playGame() {
// 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");
//Ask the user if they want to play again
//If yes, recursively call the playGame method again
//Otherwise, break out of the loop
System.out.println("Do you want to play again? (Y or N)");
String answer = kb.next();
if (answer.equalsIgnoreCase("Yes") || answer.equalsIgnoreCase("Y")) {
playGame();
}
else {
break;
}
}
} while (guess != num);
}
}
Explanation:
There are a few things you need to do.
1. Make the creation of the objects of the Scanner and Random classes global. In other words, make them global variables.
2. Create a method, say playGame(), that is called, recursively, every time the user needs to play or replay the game.
The source code file (Guesser.java) has been attached to this answer.
Note: You might want to consider also reducing the range of guess. I'd rather you reduced it to 1-10 rather than what you have. This will make the game much of a fun. With the range you currently have, the user might never guess right.
Hope it helps!