Ask Question
13 June, 11:21

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. 13 June, 11:54
    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?
Get 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 & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers