ComradeSpaceMan ComradeSpaceMan - 24 days ago 10
Java Question

One if statement taking precedence over another if, despite it being lower?

I'm trying to make an if statement that would allow the user to exit the program by typing quit. My problem lies in that another if statement I have in the same block, albeit lower down, catching to ensure that the string entered is no longer than 3 characters long (required for the program) and that if statement takes precedence and cancels out the "quit" if statement. What am I doing wrong that is causing this?

System.out.print("Guess #"+numGuess+": ");
guess = input.nextLine();
guess.toUpperCase();
if(guess == "quit" || guess == "QUIT"){
done = true;
System.out.println("You lose.");
display();
}
if(guess.length() != 3){
while(guess.length() < 3){
System.out.println("Guess too short");
System.out.print("Guess #"+numGuess+": ");
guess = input.nextLine();
guess.toUpperCase();
}
while(guess.length() > 3){
System.out.print("Guess too long");
System.out.print("Guess #"+numGuess+": ");
guess = input.nextLine();
guess.toUpperCase();
}
}

Answer

Keep things simple:

  1. Make your quitting if block return; to exit your program (after disply();)
  2. Don't use == to compare strings. Use .equals() or better .equalsIgnoreCase()