package com.company; public class Main { public static void main(String[] args) { int n = 10; Integer[] arr = {102, 140, 172, 140, 293, 69, 36, 144, 82, 44, 205, 41, 30, 10 ,193, 348, 79, 176, 396, 145, 43, 193, 132, 2, 226, 170, 43, 127, 136, 165}; int s = 0; int ost; for (int i = 0; i<n; i++){ int ch = arr[i*3]*arr[i*3+1]+arr[i*3+2]; // число, сумму цифр которого надо посчитать. for (int a = 0; a<Integer.toString(ch).length(); a++){ ost = ch%10; ch /= 10; s += ost; } System.out.print(s+" "); s = 0; } } } 

The task is to find the sum of digits of a number, by dividing with the remainder. It seems a childish mistake, but I can not find

    3 answers 3

    You have a condition in the loop

     Integer.toString(ch) 

    But then inside the loop you change the value of the variable ch, i.e. right border is changing along with it. You can do something like this:

     int len = Integer.toString(ch).length(); for (int a = 0; a< len; a++){ ost = ch%10; ch /= 10; s += ost; } 

    Also, I’ll say that it’s not necessary to calculate the length of a number, you can just write

     while(ch>0) { ... } 

      Take a pencil and a piece of paper. Execute your code step by step, writing down the intermediate values ​​of the variables (especially the length toString(ch) ). See everything.

      PS

      Note that in the cycle stopping condition, the operands are calculated at each iteration.

        Sergey, if I correctly understood the task, you need to calculate the sum of the digits in the number. That is, if the number is 102 , then the result should be 1+0+2=3 .

        I didn’t quite understand your design with three consecutive numbers, but for counting the sum of digits I did this:

         for (int i = 0; i < n; i++) { int numberOfDigits = (int) (Math.log10(arr[i]) + 1); int divider = Double.valueOf(Math.pow(10, numberOfDigits)).intValue(); int sum = 0; while (divider != 1) { sum += arr[i] % divider / (divider / 10); divider /= 10; } System.out.println("Sum of digits for " + arr[i] + "=" + sum); } 

        Execution result for your array:

         Sum of digits for 102=3 Sum of digits for 140=5 Sum of digits for 172=10 Sum of digits for 140=5 Sum of digits for 293=14 Sum of digits for 69=15 Sum of digits for 36=9 Sum of digits for 144=9 Sum of digits for 82=10 Sum of digits for 44=8 

        I hope this is what you are looking for.