Java – Comparison of two strings
•
Java
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, this code assumes to test whether the inverse of string h is equal to string s, and vice versa For some reason, it always returns "false" - although the obvious answer is correct
Who can tell me what's wrong with my code?
thank you!
Solution
I'll say an extra; Is the culprit
replace
if (s.charAt(i) != h.charAt(t--));
use
if (s.charAt(i) != h.charAt(t--))
You should always take the "safe" route That is, curly braces are used after if else statements (they can be used almost anywhere), so such errors do not occur in the first place The correct way to write it is:
if (s.charAt(i) != h.charAt(t--)) { g++; }
By the way, if you don't check that s and H are the same length first, your code will explode
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码