Question: Before the while loop, add a variable to keep track of the number of guesses the user has made. Remember to initialize this variable to
Before the while loop, add a variable to keep track of the number of guesses the user has made. Remember to initialize this variable to 1 instead of 0 since the user will need at least one guess to get the correct number. Inside the while loop, increment the variable by one each time the user guesses incorrectly. After the while loop, add a message that tells the user how many guesses they took.
Here is what I have so far:
package murach.games;
import static java.lang.System.exit; import java.util.Random; import java.util.Scanner;
public class Main {
public static void main(String[] args) { int n=0; Scanner sc = new Scanner(System.in); System.out.print("Welcome to the Number Guessing Game" + " " + " " + "Enter the upper limit for the number: "); int upper = sc.nextInt(); Random r=new Random(); n=r.nextInt(upper-1)+1;
System.out.print("OK, I'm thinking of a number between 0 and 50 ");
// System.out.println("Number : "+n); int i=0; int guess=0; while(true){ System.out.print("Enter your guess:"); guess=sc.nextInt(); if(guess > n) System.out.println("Your guess is too high:"); else if(guess < n) System.out.println("Your guess is too low:"); else if(guess == n){ System.out.println("Correct!" + " " + " " + "Bye!"); exit(0); } i++; } } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
