Friday, November 6, 2015

// // Leave a Comment

Java Program To Sum The Digits In An Integer

The program below is the answer to Liang's Introduction to Java Programming (9th Edition) Chapter 2 Exercise 2.6.

Question: Write a program that reads an integer between 0 and  1000 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digits is 14. Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 / 10 = 93.

 * @Author: Aghatise Osazuwa
 * Website:
 * Exercise 2.6 - SumTheDigitsInAnInteger

import java.util.Scanner;

public class Exercise02_06_SumTheDigitsInAnInteger {
    public static void main (String [] args) {
        Scanner input = new Scanner(;
        System.out.println("This Program Sums The Digits In An Integer Between 0 and 1000.\n");
        System.out.println("Enter a number between 0 and 1000: ");
        double number = input.nextDouble();
        double digit1 = number%10;
        double removeDigits1 = (int)number/10;
        double digit2 = removeDigits1%10;
        double removeDigits2 = (int)removeDigits1/10;
        double digit3 = removeDigits2%10;
        double sumOfDigits = digit1 + digit2 + digit3;
        System.out.printf ("The sum of the digits is " + sumOfDigits + "\n");

Click here to see other solutions to Introduction to Java Programming.


Post a Comment

DISCLAIMER: Opinions expressed in comments are those of the comment writers alone and does not reflect or represent the views of the post author. We reserve the right to delete any post deemed inappropriate or offensive and/or spammy. Please do not use abusive words/hate speech.

I Appreciate your valuable Feedback. So, Please DO NOT SPAM - Spam comments will be deleted immediately.

Don't use brand name in name field and you're not allowed to use links in comments unless it's necessary. Such comments will be removed immediately. To get notified of replies or follow-up comments, click the box next to notify me.