In: Computer Science
This is for java
For my assignment, I was supposed to make a number guessing game. The class, HiLo, should pick a random number between 1 and 100 (inclusive). Then, prompt the user to guess the number. On each guess, print if the user is correct or if the guess is too high or too low. Allow only 5 guesses. In the end, print out the correct answer and how many attempts were made.
Then give the user the option to play again (1 for yes and 0 for no).
I have tried to do this but I get stuck on making it so that there are only 5 guesses and I always get an error when asking the option to play again.
Below is your code
import java.util.Random;
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
boolean done = false;
Scanner sc = new
Scanner(System.in);
while(!done) {
int count =
0;
Random rand =
new Random();
int number =
rand.nextInt(101) + 1;
int guess;
while(count <
5) {
System.out.print("Guess a number: ");
guess = sc.nextInt();
count++;
if(guess < number) {
System.out.println("Guess is
too low.");
} else if (guess > number) {
System.out.println("Guess is
too high.");
} else {
System.out.println("Thats
correct. You guessed it right in "+count+" guesses.");
break;
}
}
if(count >=
5) {
System.out.println("Maximum tries over. You have
lost the game. Please try again.");
}
String
choice;
System.out.print("Do you want to play again ? (Y/N): ");
choice =
sc.next();
if(choice.equalsIgnoreCase("y")) {
done = false;
} else {
done = true;
System.out.println("Thanks for playing the
game.");
}
}
sc.close();
}
}