Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading