0

Whenever I run this program, everything runs fine until I get to the bottom where I'm supposed to type "y" or "n". I type "n" (without the parenthesis), and for some reason it continues to loop. Most likely, I'm improperly using. However, any help is fully appreciated! Thanks!

  import java.util.Scanner;

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

  Scanner reader = new Scanner(System.in);
  int guess = 5;
  int randomNumber;
  int guessRepetition = 1;
  String yes = "y";
  String no = "n";
  String answer;

  randomNumber = (int)(Math.random() * 24 + 1);
  System.out.println(randomNumber);

  for(;;){

     for (int x = 1; x<=4; x++) {
        System.out.println("Guess a number from 1 - 25.");
        guess = reader.nextInt();

        if(guess == randomNumber) {
           System.out.println("Guess #" + guessRepetition + " is correct.");

           if(guessRepetition == 1) {
              System.out.println("Great, you guessed the number in " + guessRepetition + " try.");
              break;
           }
           else {
              System.out.println("Great, you guessed the number in " + guessRepetition + " tries.");
              break;
           }
        }  
        else if (guess > randomNumber) {
           System.out.println("Guess # " + guessRepetition + " is too high.");
           guessRepetition ++;


        } 
        else if (guess < randomNumber) {
           System.out.println("Guess # " + guessRepetition + " is too low.");
           guessRepetition ++;

        }
     }

     if (guess != randomNumber) 
     {
        System.out.println("The number was " + randomNumber + ".");
        System.out.println("You couldn't guess the number in 4 tries, so you lose.");
     }
     System.out.println("Would you like to play again? Press 'y' or 'n'");
     answer = reader.next();

     if (answer == no)
        break;
  }

} }

Michael
  • 1
  • 1

2 Answers2

0

Change

answer == no

to

answer.equals(no)

Why? Because the == operator will compare the two variables at a reference level. Your string "answer" will contain the same characters as your string "no" but they are different objects, and as such == will return false. equals() will test the content of the two Strings instead, and return true if they contain exactly the same characters (case sensitive).

Dyrborg
  • 877
  • 7
  • 16
0

Learn the difference between == and .equals.

== compares between raw values or object references, it's only going to be equal if the object references are the same.

.equals compares objects for their content, and it's what you should be using in this case.

Pedro Montoto García
  • 1,672
  • 2
  • 18
  • 38