-1

How do I know if String letter is equal to char array

String[] choose = {"a","d","t","b","s","f","x"};
    String check;
    boolean error = false;

        System.out.print("Enter");

        Scanner sn = new Scanner(System.in);    
         check = sn.nextLine();
        for (int i = 0 ; i < choose.length;i++){

            if(choose[i] == check){
                System.out.print("you entered" + choose[i]);
                break;
            }
        }

What I did is this it didnt confirm I input letter a but "you entered" didnt show up.

  • 4
    [how-do-i-compare-strings-in-java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Pshemo Apr 02 '13 at 17:09

2 Answers2

5

You cannot test strings for equality using ==. That only compares references (memory addresses). You need to use String#equals(Object). In general == is most certainly what you don't want if you are testing for equality, unless you are checking to see if two variables are pointing to the same instance. This is rarely the case, since you are usually interested in testing values for equality.

So what you need to do is:

if(choose[i].equals(check)) {
   ...
}
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
0

You are trying to compare strings with ==, which only compares the references, but not the values. What you want to use is

if(check.equals(choose[i]))
SBI
  • 2,322
  • 1
  • 17
  • 17