Before the while loop, add a variable to keep track of the number of guesses the
ID: 3883822 • Letter: B
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 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++;
}
}
}
Explanation / Answer
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 guess=0;
int no_of_guesses=1; //variable to count no of guesses
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!");
break; //As exit quits the entire program use break instead it only breaks the loop and program continues
}
no_of_guesses++; //increment no of guesses for each iteration of while loop
}
System.out.println("NO OF GUESSES :" + no_of_guesses); //to display no of guesses
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.