I’m trying to compare an index from my array of char’s to a string, I’m using the .equals method but I’m running into errors. Any help?
if (j[1].equals("A"))
{j[1] = 10;}
I keep getting this error:
int cannot be dereferenced
else if (j[1].equals("A"))
In order to compare single characters, you need to use the
==operator becausecharis a primitive type and Java does not allow to call methods on primitive types. Also, you can’t directly compare with a string, you need to compare to achar. Constants of typecharare written with single quotes as opposed to double quotes which denote String constants.Thus your code would be:
You should then use another variable for storing the value
10. Although you could theoretically store it in the array (characters are just numbers, too), this would be very confusing code. Thus use an additionalintvariable.Also note that in Java, you should speak of
chars, not ofChars. The reason is that there is also a class nameCharacterwhich also represents a single character, but as an object instead of a primitive type. Thus when you sayChar, it is not clear if you meancharofCharacter.