Ask Question
6 November, 15:42

6.2 Sum the digits in an integer (Sum 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 sumDigits (long n) For example, sumDigits (234) returns 9 ( = 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 ( = 2 3). 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 then displays the sum of all its digits. So in your main method you'd call sumDigits () like this and print what it returns. For example: System. out. println ("Sum of the digits in the number 1234 is: " + sumDigits (1234));

+5
Answers (1)
  1. 6 November, 16:01
    0
    The method sumDigits () and the test program is given in the explanation section below:

    Explanation:

    import java. util. Scanner;

    public class num8 {

    public static int sumDigits (long n) {

    long sum = 0;

    while (n! = 0)

    {

    sum = sum + n % 10;

    n = n/10;

    }

    return (int) sum;

    }

    public static void main (String[] args) {

    System. out. println ("Enter a long integer");

    Scanner in = new Scanner (System. in);

    long digit = in. nextLong ();

    System. out. println (sumDigits (digit));

    }

    }

    The steps required to implement this method are given in the question. A while is used to repeatedly extract and remove the digit until all the digits are extracted. In the main method, the Scanner class is used to prompt a user to enter a digit, the method is called and the digit is passed as an argument.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “6.2 Sum the digits in an integer (Sum the digits in an integer) Write a method that computes the sum of the digits in an integer. Use the ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers