I have the following code:
int t = s.length()-1;
int g = 0;
for (int i=0; i < s.length(); i++){
if (s.charAt(i) != h.charAt(t--));
g++;
}
if (g==0)
return true;
else
return false;
Basically what this code is suppose to do is to test if string h’s inverse is equal to string s, or vice versa. For some reason a “false” is always returned – although the obvious answer is true.
Can anyone please tell me what’s wrong with my code?
Thanks!
I’d say an extra
;is the culprit.Instead of
use
You should always go the “safe” route. That is, use braces after if-else statements (and pretty much everywhere you can use them), so bugs like this won’t happen in the first place. The correct way to write it is:
And by the way, your code will blow up if you don’t check first that
sandhhave the same length.