Jeann Pierre Jeann Pierre - 1 month ago 9
Java Question

Checking Character in a String using .equals() not working

I'm trying to check if a letter submitted by user is contained in a string, but it always return false. From what I read the .equals() function should work. I was expecting that if a user inputs the letter "a" it would return "pass" if the string was "america".

for (int i = 0; i < outputTest.length(); i++){
if (userInput.equals(outputTest.charAt(i))){
System.out.println("Pass");
}else {
System.out.println("Fail");
}
}

Answer

Based on outputTest.length() and outputTest.charAt() I am assuming that outputTest is String.
Based on userInput.equals I am assuming it is not primitive type like char (since primitive types don't have methods). It is also not Character, otherwise you would see Pass few times. So it most likely is also String.


outputTest.charAt(i) returns char, but you are comparing it with String which equals method looks like:

964  public boolean equals(Object anObject) {
965 if (this == anObject) {
966 return true;
967 }
968 if (anObject instanceof String) {
969 String anotherString = (String)anObject;
970 int n = value.length;
971 if (n == anotherString.value.length) {
972 char v1[] = value;
973 char v2[] = anotherString.value;
974 int i = 0;
975 while (n-- != 0) {
976 if (v1[i] != v2[i])
977 return false;
978 i++;
979 }
980 return true;
981 }
982 }
983 return false;
984 }

So since equals expects Object, char (returned from outputTest.charAt(i)) will be automatically boxed to Character, but since Character doesn't extend String test

if (anObject instanceof String) 

will fail and you will immediately move to return false;.


You may want to use contains method if you want to check if one String contains another

outputTest.contains(userInput)