Disclosure: When you purchase a service or a product through our links, we sometimes earn a commission.

# Java program to find Sum of Digits in a Number

February 2, 2018

The following program takes an integer number as an input and returns the sum of the individual digits.
The number can be positive or negative.

For instance, if the user enters 456, the program returns 15 which is the sum of 4 + 5 + 6.

Additionally, the program makes sure the user enters only a valid integer (int) number.

The program is listed below:

``````
/*
This program reads individual digits of a given number and returns their sum
*/
import java.util.*;
int digit = 0;
int sum = 0;

while (number!=0){
digit = number%10;
sum += digit;
number = number/10;
}
System.out.println("The sum of the digits is: " + sum);
}
public static void main( String[] args) {
Scanner input = new Scanner(System.in);

//Prompt for input and also check validity
while( !input.hasNextInt()){
System.out.println("That is not a number, please enter a number");
input.next(); //If you use nextInt(), you might get error
}
int number = input.nextInt();
System.out.println("You entered " + number); //Show user input