Java .charAt(i) comparison issue
Solution 1
You're confusing
char zero = 0;
with
char zero = '0';
The former is the null-character (ASCII value of zero), whereas the latter is the character representing the digit zero.
This confusion is a rather unfortunate hang-over from C, with char
variables being treated as numbers as well as characters.
Solution 2
You're comparing against Unicode value 0 (aka U+0000, the "null" character) - which is not the same as the Unicode character representing the digit 0.
Use '0' instead of 0:
while(i < t.length() && zeroCount < 5) {
if(t.charAt(i) == '0'){
zeroCount++;
}
i++;
}
Solution 3
You are looking for the character '0'? Then compare to '0', not 0.
Solution 4
The simple answer is that the value 0
is not the same as the character '0'
which has an ASCII code of 48
(IIRC).
You should compare it with the char value charAt(i) == '0'
or subtract the char before comparison charAt(i) - '0' == 0
Solution 5
Use '0' instead of 0.
Carlos
Updated on July 07, 2020Comments
-
Carlos almost 4 years
Why when comparing a char against another it must be taken also from a string? For example;
This does not work
while(i < t.length() && zeroCount < 5) { if(t.charAt(i) == 0){ zeroCount++; } i++; }
Nor does this
char zero = 0; while(i < t.length() && zeroCount < 5) { if(t.charAt(i) == zero){ zeroCount++; } i++; }
The only way I managed to get it working is like this...
String zeros = "0000000000"; while(i < t.length() && zeroCount < 5) { if(t.charAt(i) == zeros.charAt(i)){ zeroCount++; } i++; }
Can anyone explain if am doing something wrong, or if it is just not acceptable to do it like the top 2 examples. If so, why?
-
tchrist over 13 yearsI’m not comfortable with telling people to use
charAt
: it’s broken by design. -
tchrist over 13 yearsI don’t think you should tell people to use the old broken
charAt
method. Too many problems. -
Ishtar over 13 yearsYour answer is confusing for someone who doesn't know about charsets. For finding
0
(or any BMP character) there is nothing wrong withcharAt
, or what problems do you mean? -
tchrist over 13 years@Ishtar: The problems I have are that character counts will be off. Something like
"\uD83D\uDCA9\uD83D\uDCA9\u0000\uD83D\uDCA9\uD83D\uDCA9"
has only 5 code points in it, with the NUL at number 3. That’s why the Java Pattern^.....$
matches it: because the Pattern class always deals in logical units, as is proper.