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.