Java . Charat (I) comparison problem
•
Java
Why do you have to get a char from a string when comparing a char with another char? For example;
It doesn't work
while(i < t.length() && zeroCount < 5) {
if(t.charAt(i) == 0){
zeroCount++;
}
i++;
}
It's not
char zero = 0;
while(i < t.length() && zeroCount < 5) {
if(t.charAt(i) == zero){
zeroCount++;
}
i++;
}
The only way I try to make it work is this
String zeros = "0000000000";
while(i < t.length() && zeroCount < 5) {
if(t.charAt(i) == zeros.charAt(i)){
zeroCount++;
}
i++;
}
Anyone can explain whether I did something wrong, or it is unacceptable to do as in the first two examples If so, why?
Solution
You're confused
char zero = 0;
with
char zero = '0';
The former is a null character (ASCII value is zero), and the latter is a character representing the number zero
This confusion is a rather unfortunate legacy of C. char variables are treated as numbers and characters
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
二维码
