0

I am fairly new to Java and am in need of help with my If/Else statement. Basically I want to make it so that if the person types in n or no do one thing, or if the person puts in y or yes, do another thing, and if the person doesn't put in n, no, yes or y than do a different thing. But no matter what the user puts in, it acts as if they did not put in n, no, yes or y. How can I fix this?

This is my code so far:

public class Main 
{
 public static void main (String[] args)
 {
    Scanner userInputScanner = new Scanner(System.in);
    String [] charName = {"John", "Bob", "Sam"};
    Random random = new Random();
    int charNameChoice = random.nextInt(charName.length);
    System.out.println("Random char selected: " + charName[charNameChoice]);
    System.out.println("Y N Question1");
    System.out.println("You can input y, yes, n or no");
    String questionOneAnswer = userInputScanner.nextLine();
    if (questionOneAnswer == "n" || questionOneAnswer == "no")
    {
        System.out.println("I disagree");
    }
    else if (questionOneAnswer == "y" || questionOneAnswer == "yes")
    {
        System.out.println("I agree");
    }
    else
    {
        System.out.println("Invalid");
    }

 }

}
  • In short - `==` compares object references not the content of the objects themselves. You should use `.equals()` for that. – JonK Oct 02 '14 at 14:18

1 Answers1

2

You should use equals to compare String values, like stringVar.equals("something"). Better yet, reversing it "something".equals(stringVar) prevents Nullpointerexceptions.

== compares the pointers, which are almost never equal (unless you're comparing String constants).

Davio
  • 4,609
  • 2
  • 31
  • 58