javacharat

Problem with suming up digits in an integer with charAt() in Java


I have one integer number and my goal is, to sum up digits in that integer

I tried with charAt(); but the weird part is when I'm trying to check numbers with their

index its works well but the part I don't understand is when I'm trying to sum them up

why 2 + 2 is 100

Scanner scanner = new Scanner(System.in);

    int number = scanner.nextInt();

    String string_number = Integer.toString(number);

    System.out.println(string_number.charAt(0));
    System.out.println(string_number.charAt(1));

    System.out.println(string_number.charAt(0) + string_number.charAt(1));

input 22

Output

2
2
100

Solution

  • A character in Java is close to its unicode code point. And the unicode code point of '2' is... 0x32 or 50!

    And yes, 50 + 50 is 100...

    Fortunately, the value of a decimal digit is guaranteed to be c - '0', so what you want is:

    System.out.println((string_number.charAt(0) - '0') + (string_number.charAt(1) - '0'));