-1

I'm fairly new to Java and am trying to create a text game, involving escaping. Here is my code:

import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Adventure {
    public static void main (String args[]) throws InterruptedException{
        System.out.println("YOU WAKE ON YOUR COUCH. YOU NEED TO GET OUT OF YOUR HOUSE.");
        int x = 1;
        while (x == 1){ 
            Scanner ACTION = new Scanner(System.in);
            System.out.println("WHAT DO YOU DO NEXT?");
            String action;
            action = ACTION.next();

            if (action == "a"){
                System.out.println("if");
            }else{
                System.out.println("else");
            }
        }
    }
}

Try running and see that the if does not work, if you enter 'a', it prints 'else'. Please explain each new line of code (if any) in your answer. Thank you.

Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
user2916424
  • 37
  • 1
  • 1
  • 3
  • What is your question? – Jeremy D Nov 28 '13 at 22:02
  • Your while loop won't stop. You don't change the value of x. You should use equals to compare string. – Jeremy D Nov 28 '13 at 22:03
  • `==` checks if two strings are literally the same string (think same piece of paper) whereas `string.equals(otherString)` checks if they have the same letters (possibly written on different pieces of paper) – Richard Tingle Nov 28 '13 at 22:04

1 Answers1

1
if (action == "a"){
    System.out.println("if");
}

You're comparing String types. Use equals.

if(action.equals("a") { }
christopher
  • 26,815
  • 5
  • 55
  • 89