0

Sorry if the question doesn't make much sense, I'm very new to Java. So here's my problem: I'm making a text adventure game (very basic at the moment) and I created a string (choice1), which is equal to the answer the player gives to a question the game asks. The answer is either supposed to be north, North, south or South. When I found that no matter what I typed it said it was an invalid answer, I made the game display what choice1 was equal to when I typed my answer. I found that when I typed north, it displayed north, when I typed south, south, etc. So it had correctly picked up what I had typed, but it still said it was an invalid answer. Here is my code (including the part that displays what choice1 is equal to):

Scanner answer = new Scanner(in);
String choice1 = answer.nextLine(); 

out.println(choice1);
if (choice1 == "north" || choice1 == "North") //If the answer is North
{
    out.println("You start walking towards the mountains in the distance. A cold wind picks up from behind you.");  
}

else if (choice1 == "south" || choice1 == "South") //If the answer is south
{
    out.println("You head into the forest and are quickly surrounded by trees. Patches of light dance on the floor to the whim");
}

else if (choice1 != "south" || choice1 != "South" || choice1 != "north" ||     choice1 != "North") //invalid answer 
{
out.println("Please enter a valid answer.");
}

answer.close();
  • As per your code requirement, I guess you want to use && instead of || for the last else if statement. As In your case, if any one of those conditions will be true then it will show "invalid answer". For eg: If you provide "north" as input it will not be equal to "south", "South" or "North" and else if condition will result in true and it will print invalid answer. – Mohit Tater Jul 16 '16 at 04:28
  • Instead of `if-else`, you could consider a `switch-case`. – cassiomolin Jul 16 '16 at 06:34

2 Answers2

3

Use String#equals() instead of == to compare Strings. For a case insensitive comparison, use String#equalsIgnoreCase().

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
0

Get use to read the documentation, you can't use == to compare Strings , if you look at Java's documentation you will find the method

  boolean equals(String s)

How to use :

  if(choice1.equals("whatever"))
  {
       // TODO the jobe here
  }
Adliano Alves
  • 311
  • 2
  • 6
  • You **can** use `==`. Otherwise, the compiler wouldn't allow you to do so. I would say you **should not** or **must not**. – cassiomolin Jul 16 '16 at 04:00
  • `choice1.equals("whatever")` will throw a `NullPointerException` if `choice1` is `null`. To avoid it, use `"whatever".equals(choice1)`. – cassiomolin Jul 16 '16 at 06:21