0

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

user3397201
  • 1
  • 1
  • 1
  • 1
  • 1
    `ic.equalsIgnoreCase("y") || ic.equalsIgnoreCase("yes")` – Joop Eggen Mar 08 '14 at 23:10
  • 1
    Never (except when you *really* understand what you're doing) use `==` to compare strings or floating-point numbers. This is true in most languages, not just Java. – Hot Licks Mar 08 '14 at 23:19

2 Answers2

1

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"))
Hugo Sousa
  • 1,904
  • 2
  • 15
  • 28
0

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")

TouDick
  • 1,262
  • 12
  • 18