Comparing array index with string?

I am trying to compare an index from my char array with a string, I am using the .equals method, but I am getting 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"))

      

+3


source to share


3 answers


To compare single characters, you need to use an operator ==

because it char

is a primitive type and Java does not allow calling methods on primitive types. Also, you cannot directly compare to a string, you need to compare with char

. Type constants are char

written with single quotes, not double quotes, which denote string constants.

So your code will look like this:

if (j[1] == 'A') 

      



Then you have to use another variable to store the value 10

. While it is theoretically possible to store it in an array (characters are also numbers), it would be very confusing code. Thus, use an extra variable int

.

Also note that in Java you should be talking about char

s, not char

s. The reason is that there is also a class name Character

that also represents a single character, but as an object instead of a primitive type. Thus, when you speak char

, it is not clear if you have char

Character

.

+2


source


Try this instead:

if (j[1] == 'A')

      



If the array j

contains char

s, you should compare its values ​​with another char

, not with String

(even if the string is 1 in length) - these are different data types. And since a char

is a primitive type, it is ==

used for equality comparison.

+3


source


If j [1] is an array char

(primitive, not an object Character

), you cannot call the equals method on it, just as you cannot call 1.equals("A")

.

So this will work (using objects)

    char[] array = new char[] { 'a', 'b', 'c' };
    boolean equals = array[0].equals('a'); // Cannot invoke equals(char) on
                                            // the primitive type char
    Character.valueOf('a').equals(Character.valueOf(array[0])); //This works

      

Or this using primitives:

    char[] array = new char[] { 'a', 'b', 'c' };
    boolean anotherEquals = array[0] == 'a'; // This works

      

0


source







All Articles