0

The following code won't run the way it's supposed to. The output is always "That isn't a valid answer!"

The code that I'm referring to is as follows:

System.out.println("Should you move along the road or continue through the forest?");
String anw = scan.next();
if (anw == "forest") {
    System.out.println("You decide to go to the forest, it's dark and creepy but it can't hurt, right?");
} else if (anw == "road") {
    System.out.println("You decided to go along the road and hope to find something, anything, there.");  
} else {
    System.out.println("That isn't a valid answer!");
} 

Any help will be more than appreciated, thank you!

bpoiss
  • 13,673
  • 3
  • 35
  • 49
thebestofu
  • 21
  • 3
  • 1
    Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Feb 11 '16 at 16:00
  • So instead of `if (anw == "forest") {`, you'd do `if ("forest".equals(anw)) {` or `if ("forest".equalsIgnoreCase(anw)) {` – Hovercraft Full Of Eels Feb 11 '16 at 16:01
  • 1
    I've formatted your code for readability, but in the future I strongly recommend that you do this yourself. Formatting is very important because if your code is not in a standard accepted format, it's not very readable, and if it's not readable, it's not understandable. – Hovercraft Full Of Eels Feb 11 '16 at 16:02

0 Answers0