Sum of Digits Java Program
Introduction
In this post, we will write a java program to calculate the sum of digits of a number. We will take input from the user with a prompt to enter the number.
Eclipse IDE Setup
Some steps and instructions to create a Java application on Eclipse IDE:
- Create Java Project in Eclipse
https://www.testingdocs.com/create-a-new-java-project-in-eclipse/
- Create Java Package in Eclipse
https://www.testingdocs.com/create-java-package-in-eclipse-ide/
- Create Java Class in Eclipse
https://www.testingdocs.com/create-a-new-java-class-in-a-project/
- Run Java Project in Eclipse
https://www.testingdocs.com/run-java-project-in-eclipse/
Java Program
import java.util.Scanner; /************************************************** * DigitSum.java * @program : DigitSum to calculate the sum of * digits in the number. * @web : www.TestingDocs.com * @version : 1.0 **************************************************/ public class DigitSum { private int number; private int sum; /** * @return the number */ public int getNumber() { return number; } /** * @param number the number to set */ public void setNumber(int number) { this.number = number; } /** * @return the sum */ public int getSum() { return sum; } /** * @param sum the sum to set */ public void setSum(int sum) { this.sum = sum; } /** * @param number * @param sum */ public DigitSum(int number) { this.number=number; this.sum = 0; } private void calculateSum() { int remainder = number; int digit = 0; while(remainder > 0) { digit= remainder%10; remainder= remainder/10; this.sum= this.sum + digit; } } public static void main(String args[]) { int number=0; Scanner keyboard = new Scanner(System.in); System.out.println("Enter number :="); number = keyboard.nextInt(); DigitSum ds= new DigitSum(number); ds.calculateSum(); System.out.println("Sum of Digits := " + ds.getSum()); } }
Program Output
Enter number :=
1687
Sum of Digits := 22
Screenshot
—
Java Tutorials
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :