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?