Skip to content

Instantly share code, notes, and snippets.

@eMahtab
Created November 19, 2015 05:40
Show Gist options
  • Save eMahtab/cd47e7c0ad474f5e9a0d to your computer and use it in GitHub Desktop.
Save eMahtab/cd47e7c0ad474f5e9a0d to your computer and use it in GitHub Desktop.
Java program to calculate Sum of Digits of a number
public class SumOfDigits{
public static void main(String args[]){
System.out.print("Enter a number : ");
long number=-9999,input=-9999;
try{
number=Long.parseLong(System.console().readLine());
input=number;
}catch(NumberFormatException nfe){
System.err.println("Error : Please enter a valid number");
System.exit(1);
}
System.out.println("Number: "+number);
//Actual Logic for calculating Sum of Digits of a number
long remainder=0,total=0;
while(number > 0){
remainder=number % 10;
total+=remainder;
number=number/10;
}
System.out.println("Sum of the Digits of number "+input+" is "+total);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment