I'm writing a simple program and in it I need to get a user's input for yes/no (I'm using Scanner, UI, for this) like so:
System.out.println("Do you know the insulation capacity? (y/n) "); String IC = UI.nextLine(); And that works perfectly fine, but I have trouble in the next section, where I check the string in an if statement:
if(IC == "y" || IC == "Y" || IC == "yes" || IC == "Yes"){ //four options of saying "yes" System.out.print("What is the insulation capacity? "); m = UI.nextDouble(); }else if(IC == "n" || IC == "N" || IC == "no" || IC == "No"){ //four options of saying "no" findM(); }else{ System.out.println("Answer was not clear. Use y, n, yes, or no."); checkM(); } When I run the program, the else is always executed, even if IC is Y, y, Yes... etc.
Why is this the case and how do I get this to work?
Thanks,
-Justice
22 Answers
You should compare Strings with equals instead of ==. Otherwise, you'll be comparing the references, not their value, which is what you want.
Also, in this case equalsIgnoreCase may be helpful for you. You would only need 2 comparisons instead of 4.
Example:
if(IC.equalsIgnoreCase("y") || IC.equalsIgnoreCase("yes")) You cannot compare Strings in Java using == operator. Use equals instead as for every Object-Type. In your case best solution is to use condition like ic.equalsIgnoreCase("y") || ic.equalsIgnoreCase("yes")
2