Hello! The sumDigitsInNumber method should return the sum of digits of the received number (546), but instead returns the sum of the number codes from the ASCII table (returns 159, the sum of the codes is 53 + 52 + 54), learn Java for less than a week and cannot understand what the problem is, tried to google , but did not google. Help me please)

PS I ran into a problem not only in this program, for myself I wrote the program "guess the number" and there, when entering a number from the keyboard via BufferedReader, the character code was also returned (

Thank you in advance!)

public class Solution { public static void main(String[] args) { System.out.println(sumDigitsInNumber(546)); } public static int sumDigitsInNumber(int number) { String s = Integer.toString(number); char[] chars = s.toCharArray(); number = 0; for (int i = 0; i < chars.length; i++) { number += (int) chars[i]; } return number; } } 

    3 answers 3

    Did literally the other day, but in two other ways. Here my package names are used.

    The main class SumOfDigits.java:

     package info.sjd; import java.util.logging.Logger; import info.sjd.service.SumOfDigitsService; public class SumOfDigits { private static Logger logger = Logger.getLogger(SumOfDigits.class.getName()); public static void main(String[] args) { int number = 12345; int sumOfDigitsByIntegerDivision = SumOfDigitsService.sumOfDigitsByIntegerDivision(number); int sumOfDigitsByCharSplitting = SumOfDigitsService.sumOfDigitsByCharSplitting(number); logger.info("The sum of digits of number " + number + " by integer division is " + sumOfDigitsByIntegerDivision); logger.info("The sum of digits of number " + number + " by character splitting is " + sumOfDigitsByCharSplitting); } } 

    SumOfDigitsService.java service class:

     package info.sjd.service; public class SumOfDigitsService { public static int sumOfDigitsByIntegerDivision(int number) { int sumOfDigits = 0; while (number > 0) { sumOfDigits = sumOfDigits + (number % 10); number = number / 10; } return sumOfDigits; } public static int sumOfDigitsByCharSplitting(int number) { int sumOfDigits = 0; String stringNumber = String.valueOf(number); for (int i = 0; i < String.valueOf(number).length(); i++) { sumOfDigits = sumOfDigits + Integer.parseInt(String.valueOf(stringNumber.charAt(i))); } return sumOfDigits; } } 

    In your case, you will most likely need to deal with type casting and it is possible to use the override of the .toString method ()

    ========== UPDATED =================

    Yes, with coercion of types understand. Everything works, if so: package info.sjd;

     public class Solution { public static void main(String[] args) { System.out.println(sumDigitsInNumber(546)); } public static int sumDigitsInNumber(int number) { String s = Integer.toString(number); char[] chars = s.toCharArray(); number = 0; for (int i = 0; i < chars.length; i++) { number += Integer.parseInt(String.valueOf(chars[i])); } return number; } } 
    • Yes, with coercion of types understand. Everything works, if so: package info.sjd; public class Solution {public static void main (String [] args) {System.out.println (sumDigitsInNumber (546)); } public static int sumDigitsInNumber (int number) {String s = Integer.toString (number); char [] chars = s.toCharArray (); number = 0; for (int i = 0; i <chars.length; i ++) {number + = Integer.parseInt (String.valueOf (chars [i])); } return number; }} - Vitaliy Tretyakov
    • Thank you) But still, if not difficult, can you explain why in my version returns ASCII code and not a character? - Verlonar
    • I myself am new to Java, just doing it longer than you. Therefore, I can not clearly explain. I had to solve many problems on the same codewars.com for example. Regarding the conversion of char to int is simply and clearly written here - javatpoint.com/java-char-to-int . In general, with regard to type conversion in Java, all this must be experienced, passed through itself on a variety of tasks. Then you will feel intuitively. - Vitaliy Tretyakov
    • Thank you very much)) - Verlonar

    Cast char to int returns the character code, not its numeric value. This is a documented behavior. To get a numerical value, you can use Character.getNumericValue(char) .

      Adaptation of the algorithm from the question:

       public static int sumDigitsInNumber(int number) { int sum = 0; for (char c : Integer.toString(number).toCharArray()) { sum += Character.getNumericValue(c); } return sum; } 

      Another approach:

       public class Solution { public static void main(String[] args) { System.out.println(sumDigitsInNumber(546)); // 15 } public static int sumDigitsInNumber(int number) { int sum = 0; while (number > 0) { sum += number % 10; number /= 10; } return sum; } } 

      Explanation:

      • number % 10 - returns the last digit of the number: for 546 - 6, for 15 - 5.
      • number /= 10 - reduces the number by 1 digit: 546 -> 54, 15 -> 1

      You can use Stream from java8:

       public static int sumDigitsInNumber(int number) { return Arrays .stream(Integer.toString(number).split("")) // ΠšΠΎΠ½Π²Π΅Ρ€Ρ‚ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ Π² массив String .mapToInt(Integer::parseInt) // ΠšΠΎΠ½Π²Π΅Ρ€Ρ‚ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ ΠΊΠ°ΠΆΠ΄ΠΎΠΉ строки Π² число .sum(); // ΠŸΠΎΠ΄ΡΡ‡Π΅Ρ‚ суммы }