When I try to multiply charAt I received \"big\" number:
String s = \"25999993654\";
System.out.println(s.charAt(0)+s.charAt(1));
Result : 103<
Yes - you should parse extracted digit or use ASCII chart feature and substract 48:
public final class Test {
public static void main(String[] a) {
String s = "25999993654";
System.out.println(intAt(s, 0) + intAt(s, 1));
}
public static int intAt(String s, int index) {
return Integer.parseInt(""+s.charAt(index));
//or
//return (int) s.charAt(index) - 48;
}
}
char
is an integral type. The value of s.charAt(0)
in your example is the char
version of the number 50 (the character code for '2'
). s.charAt(1)
is (char)53
. When you use +
on them, they're converted to ints, and you end up with 103 (not 100).
If you're trying to use the numbers 2
and 5
, yes, you'll have to parse them. Or if you know they're standard ASCII-style digits (character codes 48 through 57, inclusive), you can just subtract 48 from them (as 48 is the character code for '0'
). Or better yet, as Peter Lawrey points out elsewhere, use Character.getNumericValue, which handles a broader range of characters.