5.2 (Summing the digits in an integer) Write a method that computes the sum of t
ID: 3625096 • Letter: 5
Question
5.2 (Summing the digits in an integer)
Write a method that computes the sum of the digits in an integer.
Hint
Use the % operator to extract digits and
use 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.
*/
HELP! Will rate Lifesaver!!!
This is what I have
import java.util.Scanner;
public class Exercise5_2 {
public static void main(String[] args) {
// Eneter a positive integer: Scanner(System.in)
//Call method sumDigits and then display the result
}// end of main
public static int sumDigits (long n) {
int temp = (int)Math.abs(n); // temp value
int sum = 0; // the sum of the digits
// while (loop until all the digits are extracted) {
// extract a digit (%)
// add the extracted digit into sum
// remove the extracted digit (/)
//}
// return the sum of the digits
return sum;
} // end of sumDigits
}
// end of Exercise 5_2
/* Sample Run
Enter a number: 234
The sum of digits for 234 is 9
*/
Explanation / Answer
import java.util.Scanner; public class Exercise5_2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int integer = input.nextInt(); /// call method sumDigits and then display the result System.out.println("Sum is: " + sumDigits(integer)); } // end of main public static int sumDigits(long n) { int temp = (int)Math.abs(n); // temp value int sum = 0; // the sum of the digits // while (loop until all the digits are extracted) while (temp > 0) { // Extract off a digit, add it to sum sum += temp % 10; // Now set temp to the value minus the extracted digit temp = temp / 10; } // return the sum of the digits return sum; } // end of sumDigits }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.