//Exercise5_2.javac: Create a method for summarizing digits in an int
/*
Page 188
5.2 (summing the digits in an integer)
Write a method that computes the sum of the digits in an integer.
Use the following method header:
public static int numDigits(long n)
For example, sumDigits(234) returns 2 + 3 + 4 = 9.
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 off all its digits.
*/
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 positive integer: ");
int integer = input.nextInt();
/// 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)
while (temp > 0)
// subtract 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
/* Output
The sum of digits for 234 is 9
*/
Okay I'm doing this for my class and I'm not sure how to put the code in for how the directions say. Input variables and right order to put them and what not. Anything is appreciated.

New Topic/Question
Reply



MultiQuote




|