Can I multiply charAt in Java?

后端 未结 2 1027
渐次进展
渐次进展 2021-01-28 15:29

When I try to multiply charAt I received \"big\" number:

String s = \"25999993654\";
System.out.println(s.charAt(0)+s.charAt(1));

Result : 103<

相关标签:
2条回答
  • 2021-01-28 16:11

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-28 16:17

    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.

    0 讨论(0)
提交回复
热议问题