Please help with my code!

I just started programming with java and I have started to make a text-based game, Here is the code:
The problem is every time I run it and type either ‘left’ or ‘right’ it prints out “Unknown Command”

import javax.swing.JOptionPane;


public class netProject1 {
	public static void main(String[] args) {
		String userInput = JOptionPane.showInputDialog("What's your name?");
		System.out.println("Hello " + userInput + "!");
		System.out.println("");
		System.out.println("Let's Play!");
		String userInput1 = JOptionPane.showInputDialog("Do you go left or right?");

		String room = "";
		
        if (userInput1 == "left") {
            room = ("Kitchen");
    		System.out.println("You are in the "+room);	
        } else if (userInput1 == "right") {
            room = ("Living Room");
    		System.out.println("You are in the "+room);	
        } else {
            System.out.println("Unknown Command");
        }	
	}
}

Use equals not ==.


if ("left".equals(userInput1)) ...

btw when you want to use the console also as input you can do it like this


        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        String line = console.readLine();

I agree with above, when comparing strings, be careful and do the following:


String string = "string";
String anotherString = "STRING";

//Compare 'case-matching'
if(string.equals(anotherString)) {
  //string matches anotherString
}

//Compare 2 strings disregarding case
if(string.equalsIgnoreCase(anotherString)) {
  //string matches anotherString with a possibility of different case
}

This is a better explaination: http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java

Thanks!

I suggest if you are trying to make a text-based game that you get input from the console rather than from a frame being created. Then it would seem more natural. Also, for your directions you should really use .equalsIgnoreCase(String anotherString). It’ll really help out your left and right, because I spelled it with a capital letter.

Another option, if case doesn’t matter is to simply set the input to lower case up front.


String userInput1 = JOptionPane.showInputDialog("Do you go left or right?").toLower();

Now you don’t have to worry about using equalsIgnoreCase() everywhere.

equalsIgnoreCase() is better since you won’t lost your original String.

String is immutable. Everytime you change it, you need to recreate it. That’s what equalsIgnoreCase was written for.

Hmmmmm

Dang right!