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.
1 2 |
/**<br /> *<br /> * @Author: Aghatise Osazuwa<br /> * Website: www.cscprogrammingtutorials.com<br /> *<br /> * Exercise 2.6 - SumTheDigitsInAnInteger<br /> *<br /> */ <br /><br />import java.util.Scanner;<br /><br />public class Exercise02_06_SumTheDigitsInAnInteger {<br /> public static void main (String [] args) {<br /> Scanner input = new Scanner(System.in);<br /> System.out.println("This Program Sums The Digits In An Integer Between 0 and 1000.n");<br /> System.out.println("Enter a number between 0 and 1000: ");<br /> double number = input.nextDouble();<br /> double digit1 = number%10;<br /> double removeDigits1 = (int)number/10;<br /> double digit2 = removeDigits1%10;<br /> double removeDigits2 = (int)removeDigits1/10;<br /> double digit3 = removeDigits2%10;<br /> <br /> double sumOfDigits = digit1 + digit2 + digit3;<br /> <br /> System.out.printf ("The sum of the digits is " + sumOfDigits + "n");<br /> }<br />}<br /> |
Click here to see other solutions to Introduction to Java Programming.