I'm creating a random number guessing game and I need it to break the while loop when the user does not enter Y to continue or guesses correctly. I'm pretty sure its bad practice to use two break statements, otherwise that works. The final IF statement looks like it would work but is not throwing error or being recognized, as it just ends the loop regardless if Y is input. Is it even possible to use a break in the first condition of an IF statement or is there another way to use that final IF statement? Any sort of suggestions or help is appreciated.
Java:
import java.util.Scanner;
public class Project1 {
public static void main(String[] args) {
int targetValue = (int)(Math.random() * 100); //Stores random number as targetValue
int numberOfGuesses = 0; //Stores number of guesses as numberOfGuesses
while (true) { // Creates a loop until correctly answered with Y or N
System.out.println("Guess a number between 1 and 100."); //Asks user input
Scanner input = new Scanner(System.in); //Allows user input
int guessValue = input.nextInt(); //Stores user input as guessValue
if (guessValue == targetValue) { //Compares guessValue and targetValue
System.out.println("You guessed correctly!");
numberOfGuesses += 1;
} else if (guessValue < targetValue) {
System.out.println("Sorry, that was too low.");
numberOfGuesses += 1;
} else {
System.out.println("Sorry, that was too high.");
numberOfGuesses += 1;
}
System.out.println("You have played " + numberOfGuesses + " time(s)."); //Shows number of guess
System.out.println("Would you like to play again?"); // Ask to play again
System.out.println("(Enter Y for yes)"); //Explains how to answer
String playAgain = input.next(); //Allows user input to play again
if (!playAgain.equals("Y") || !playAgain.equals("y") || guessValue == targetValue) { //Compares user input to repeat or break loop
System.out.println("Thanks for playing!");
break;
} else {
System.out.println("Okay, good luck!");
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire