0

I am a beginner and practicing arrays in java by a game of tic tac toe. However I seem to face an error when I try to compare an array element and a string (user generated by Scanner). Here is a separate program describing my problem:

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String input = s.nextLine();

        String[] nums = {"1","2","3","4","5"};

        for (int i = 0; i < nums.length; i++) {
            System.out.println(input == nums[i]);
        }

        s.close();
    }
}

Output:

false
false
false
false
false

But when I manually set the String in place of input, it works correctly.

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String input = s.nextLine();

        String[] nums = {"1","2","3","4","5"};

        for (int i = 0; i < nums.length; i++) {
            System.out.println("4" == nums[i]);
        }

        s.close();
    }
}

Output:

false
false
false
true
false

I'm stuck. Any help will be appreciated.

  • If you would like to really to understand what's going on "under the hood" - start here: https://stackoverflow.com/questions/2486191/what-is-the-java-string-pool-and-how-is-s-different-from-new-strings – PM 77-1 Feb 29 '20 at 18:20
  • Thank you very much. I got it – Anikin Skywalker Feb 29 '20 at 18:21

0 Answers0