Msinger
Msinger

Reputation: 59

comparing the content of two char values

I'm trying to compare the content of two char values, but I'm getting the: "Cannot invoke equals(char) on the primitive type char" Error. I know the problems is on line 5 but I don't know how to overcome this problem, any ideas?

  public static int charPosition(String word, char letter){
       int answer=0, x;
       char [] charArray = word.toCharArray();
       for( x=0; x< word.length(); x++){
           if(charArray[x].equals(letter)){ answer =x;}
           else{ answer= -1;}
       }
        return answer;
   }

Upvotes: 0

Views: 1435

Answers (3)

Vinod Kumawat
Vinod Kumawat

Reputation: 741

You have to use == operator to compare character or primitive data type. Equals method used for object and string comparison.

public static int charPosition(String word, char letter){
           int answer=0, x;
           char [] charArray = word.toCharArray();
           for( x=0; x< word.length(); x++){
               if(charArray[x]==letter){ answer =x; break;}
               else{ answer= -1;}
           }
            return answer;
       }

I hope this would be helpful.

Upvotes: 1

Bruno Peres
Bruno Peres

Reputation: 16365

Char is a primitive type. It do not have methods that you can invoke from. To compare primitive types (char, int, boolean, float, double, etc) you should use ==.

.equals is a method from the Object class. The docs says:

equals(Object obj) : boolean

Indicates whether some other object is "equal to" this one.

When comparing strings you should use .equals because the class String inherits from Object.

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074178

When comparing char, you use ==, not .equals. The latter is for comparing objects (like Strings), not primitives like char.

So:

public static int charPosition(String word, char letter) {
    int answer = 0, x;
    char[] charArray = word.toCharArray();
    for (x = 0; x < word.length(); x++) {
        if (charArray[x] == letter) {     // <−−−−−− Change is here
            answer = x;
        } else {
            answer = -1;
        }
    }
    return answer;
}

But, there's more wrong with that loop:

  1. You need to terminate the loop when you find the character, and

  2. You should start with answer set to -1, and

  3. As long as you have an array, you may as well use its length instead of String's length():

So:

public static int charPosition(String word, char letter) {
    int answer = -1, x;
    char[] charArray = word.toCharArray();
    for (x = 0; x < charArray.length; x++) { // <−−−
        if (charArray[x] == letter) {        // <−−−
            answer = x;
            break;                           // <−−−
        }
    }
    return answer;
}

Upvotes: 4

Related Questions