-1

This is a program that runs a Conways Game of Life simulation. The main method is here:

public static void main(String Args[]) {
    int x = 0;
    int y = 0;
    boolean cellState[][] = new boolean[][]{};
    boolean newCellState[][] = new boolean[][]{};
    String answer;
    Scanner input = new Scanner(System.in);

    while (true) {
        System.out.print("\n Type anything for next generation, 'new' for new grid, or 'stop' to end>> ");
        answer = input.nextLine();
        if (answer == "new") {
            cellState = newCells(cellState);
        } else if (answer == "stop") {
            break;
        } else {
            System.out.println("Not an option yet");
        }
    }
}

No matter what answer is entered it will skip past the if statements and return to the beginning of the loop.

It has nothing to do with the actual contents of the statements as far as I can tell, but its might have to do with the boolean expressions.

Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
Eclipse999
  • 25
  • 4

3 Answers3

3

You should use .equals() to compare Strings and not ==.
== is used to check object references, while .equals() checks the String values.
Use: if(answer.equals("new")) and you should be golden.
It has been explained very thoroughly here.

Community
  • 1
  • 1
Idos
  • 15,053
  • 14
  • 60
  • 75
  • Since strings are immutable in java, does this mean that `input.nextLine()` creates a new `String` object which won't be the same reference as the "new" or "stop" String objects? – Atri Jan 17 '16 at 18:47
  • input.nextLine() returns a String Object which is not equal by reference to the string literal "new" or "stop" – Idos Jan 17 '16 at 18:56
0

Strings can be compared with == as well, if and only they are internalized. Strings initialized with double quotes are already internalized.

So, in your case, you can do just this.

answer = input.nextLine().intern();

UserAlpha
  • 101
  • 1
  • 7
  • While this will work, I would advise against using this if unaware of implications. http://stackoverflow.com/questions/1091045/is-it-good-practice-to-use-java-lang-string-intern – Idos Jan 17 '16 at 19:02
  • Well, ideally, you should use equals on any object for comparison. I'm saying string has a special case where it can be compared with == since java maintains a table of values for performance improvement. – UserAlpha Jan 17 '16 at 22:48
0

I'll recommend to do it like this:

if ("new".equals(answer)) {
   cellState = newCells(cellState);
} else if ("stop".equals(answer)) {
   break;
} else {
   System.out.println("Not an option yet");
}
iviorel
  • 312
  • 3
  • 10