Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m writing a code for a random number guessing game. I basically have everythi

ID: 658206 • Letter: I

Question

I'm writing a code for a random number guessing game. I basically have everything figured out except I need the whole thing to run as a while loop so that at the end I can prompt the player to answer whether they want to play again ("Y/N") and then it'll restart the program from the beginning but I don't know the best way to do that now. My current code is below. as you can see I already have put it in a while loop but I don't know the best way to go about finishing it. I also need to create an overall results report that gives - number of games played, total guesses, average guesses per game, and the best game the player played (game with least amount of guess):

import java.util.*; //so I can use scanner

public class GuessingGame {
public static void main(String[] args) {

Random rand = new Random ();
int max = 1000;
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
boolean playAgain = true;
  
while (playAgain == true) {
  
System.out.println("I'm thinking of a number between 1 and " + max + "...");

while (win == false) {

System.out.print("Your guess? " + numberToGuess);
guess = input.nextInt();
numberOfTries++;
  
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}

System.out.print("Do you want to play again? ");

}
}
}
}

Explanation / Answer

import java.util.*;

public class GuessingGame {
public static void main(String[] args) {

Random rand = new Random ();
int max = 1000;
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
boolean playAgain = true;
  
while (playAgain == true) {
  
System.out.println("I'm thinking of a number between 1 and " + max + "...");

while (win == false) {

System.out.print("Your guess? " + numberToGuess);
guess = input.nextInt();
numberOfTries++;
  
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}

System.out.print("Do you want to play again? ");

}
if(overall result report == 2000){
System.out.println("total no of played games" + "no of guess");


}
}