Feb 2, 2018 at 1:46 pm Java

Java program to find Sum of Digits in a Number

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.*;
 public class AddDigits {
     public static void addDigits(int number){
	 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) {
	 System.out.println("Please enter a number ");
	 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
	 addDigits(number); //Display sum of digits

     }
}

 

Typical output:

Please enter a number
8792345
You entered 8792345
The sum of the digits is: 38

Leave a Reply

Your email address will not be published. Required fields are marked *