Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. /*CMPS161
  2. *Program Assignment 06
  3. *
  4. *
  5. Page 234
  6. 6.2 (Sum the digits in an integer)
  7. Write a method that computes the sum of the digits in an integer.
  8. Use the following method header:
  9.  
  10. public static int sumDigits(long n)
  11.  
  12. For example, sumDigits(234) returns 9 (2 + 3 + 4).
  13.  
  14. Hint:
  15. Use the % operator to extract digits, and
  16. use the / operator to remove the extracted digit.
  17. For instance, to extract 4 from 234, use 234 % 10 (= 4).
  18. To remove 4 from 234, use 234 / 10 (= 23).
  19. Use a loop to repeatedly extract and remove the digit until
  20. all the digits are extracted.
  21. Write a test program that
  22. prompts the user to enter an integer and
  23. displays the sum of all its digits.
  24. */
  25.  
  26. import java.util.Scanner;
  27.  
  28. public class Exercise6_2 {
  29. public static void main(String[] args) {
  30. // Enter a postive integer: Scanner(System.in)
  31. Scanner input = new Scanner(System.in);
  32. System.out.println("Enter a positive integer: ");
  33. int userInput = input.nextInt();
  34. //Call method sumDigits and then display the result
  35. sumDigits (userInput);
  36. System.out.println(userInput);
  37. }
  38. // end of main
  39.  
  40. public static int sumDigits(int n) {
  41. int temp = (int)Math.abs(n); // temp value
  42. int sum = 0; // the sum of the digits
  43.  
  44. while (sum > 0) {
  45. sum = sum + temp % 10;
  46. temp = temp / 10;
  47.  
  48. System.out.print(sum);
  49.  
  50.  
  51. }
  52. return sum;
  53. }
  54. }
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65. /*int temp = (int)Math.abs(n); // temp value
  66. int sum = 0; // the sum of the digits
  67.  
  68. // while (loop until all the digits are extracted) {
  69. // extract a digit (%)
  70. input % 10
  71. // add the extracted digit into sum
  72. // remove the extracted digit (/)
  73.  
  74. // }
  75. // return the sum of the digits
  76. return sum;
  77. } // end of sumDigits
  78. } // end of Exercise6_2
  79.  
  80. /* Sample Run
  81. Enter a number: 234
  82. The sum of digits for 234 is 9
  83. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement