Problem Statement ?
- Given a number or integer in java, we would like to calculate the sum of all digits.
Examples:
- Example 1:
- If input number is 299.
- So, Sum of all digits of integer is 2 + 9 + 9 = 20
- Example 2:
- If input integer is 1234
- Sum of all digits of given number is 1+2+3+4 = 10
- We will read the input integer from console using Scanner class.
- We have used try-with-resource statement, so that Scanner can be closed automatically.
Program: calculate Sum of all digits of integer in java
package org.learn; import java.util.Scanner; public class SumOfDigits { private static int sum( int number) { int sumOfAllDigits = 0 ; while (number > 0 ) { sumOfAllDigits = sumOfAllDigits + number % 10 ; number = number / 10 ; } return sumOfAllDigits; } public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.print( "Enter the input number: " ); int input = scanner.nextInt(); System.out.println( "Sum of all digits is : " + sum(input)); } } } |
Output: sum of all digits of integer/number in Java
Enter the input number: 299 Sum of all digits is : 20 |