Marvin Porte wrote:Error: if((str.charAt(i)).equals('x')){
Cannot invoke equals(char) on the primitive type char
I can't understand the error. For me it must run just fine. Please Explain to me the meaning. Thanks!
There are two major types of variable in Java: primitives and reference types (or 'objects').
A
char is a primitive; a
Character (or indeed a
String) is an object, and therefore a reference type. You use '==' with primitives and
.equals() with objects.
String.charAt() returns a
char, so the message was telling you that
.equals() is not appropriate.
So your condition should be:
if (str.charAt(i) == 'x') { ...
However, it's nice to see a beginner err on the side of using
equals() rather than the other way around. Keep it up.
You can also string the two conditions together with '&&' rather than nesting them.
Minor efficiency point: You are allowed to define more than one variable in a
for loop, viz:
for(int i = 0, e = str.length()-1; i < e; i++) { ...
which saves the loop having to evaluate
str.length()-1 every time.
Winston
PS: You might also want to look at
String.indexOf(String, fromIndex) because it'll save you having to do the second check; but what you have looks fine, so don't worry about it too much.