user133466
user133466

Reputation: 3415

Writing an enhanced for loop in Java

I'm trying to convert the following for loop into an enhanced for loop

        for(int i=0; i< vowels.length; i++){
            if(vowels[i] == Character.toLowerCase(c)){
                return true;
            }
        }
        return false;

This is what I got, but I got i == Character.isLetter(c) underlined because The operator == is undefined for the argument type(s) char, boolean. what's wrong here?

        for(char i: vowels){
            if(i == Character.isLetter(c)){
                return true;
            }
        }
        return false;

Upvotes: 1

Views: 210

Answers (2)

Fred Foo
Fred Foo

Reputation: 363567

You must have meant

for (char v: vowels){
    if (Character.isLetter(v)) {
        return true;
    }
}
return false;

Right now, you're comparing a char to the boolean resulting from the isLetter check.

(I changed the variable name to v to emphasize that it's a vowel, not an index.)

Upvotes: 0

kosa
kosa

Reputation: 66637

Character.isLetter(c) returns boolean not char. You can't compare boolean with char.

You may need to do something like below:

 for(char i: vowels){
          boolean isChar = Character.isLetter(c);
           if(isChar){
            if(i ==c){
                return true;
            }
         }
        }

EDIT: After your comment: Your code should be something like:

for(char i: vowels){
        if(i == Character.toLowerCase(c)){
            return true;
        }
    }

Note: Hand typed code, there may be syntax errors.

Upvotes: 2

Related Questions