-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
SumDigits.java
34 lines (24 loc) · 977 Bytes
/
SumDigits.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.codefortomorrow.intermediate.chapter11.practice;
/*
Write a method that computes the sum of the digits
in an integer. Use the following method header:
public static int sumDigits(long n)
For example, sumDigits(234) returns 9 (because 2 + 3 + 4).
Hint: Use the % operator to extract digits,
and the / operator to remove the extracted digit.
For instance, to extract 4 from 234, use 234 % 10 (= 4).
To remove 4 from 234, use 234 / 10 (= 23).
Use a loop to repeatedly extract and remove the digit
until all the digits are extracted.
Write a test program that prompts the user to enter an integer and
displays the sum of all its digits.
Bonus points for writing a JavaDoc comment for the sumDigits method.
Adapted from Exercise 6.2, Introduction to Java Programming (Comprehensive),
10th ed. by Y. Daniel Liang
*/
public class SumDigits {
public static void main(String[] args) {
// test sumDigits here
}
// write sumDigits method here
}