0

I was coding a user input loop for a class project, and I ran into a roadblock where a string wasn't being accepted by comparison operators after it had been altered by scanner.nextline() input. Here is the block of code in question:

String answer = "Y";    //Initializes answer to default yes
String firstName, lastName;
int age;

//Loops to obtain user input until they no longer answer yes
while (answer == "Y" || answer == "y") {
    //Asks user if they want to add new Person to PersonQueue
    System.out.print("\nWould you like to add anyone new to the queue? Y or N\n");
    answer = scan.nextLine();

    //Obtains input
    if ((answer.equals("Y") || answer.equals("y"))) {
        System.out.println("Please enter their information...");
        System.out.print("First Name: ");
    ...........................................

I was trying to get it to work by using the same comparison in the 'if' loop as I had used in the 'while' loop, using '==' rather than 'equals'. No matter what I did it wouldn't return true, but I was sure that the answer variable still held "Y". So, after a lot of testing, I decided to try out what you see above, and it worked.. but I have no idea why.

Can someone explain to me why nextLine() changed the string in such a way that the comparison no longer recognized it as had before?

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
  • Don't use == to compare Strings in Java. Use equals(). See any Java tutorial. Or this: https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839 – passer-by Apr 10 '22 at 03:21

0 Answers0