Q:

Write a Java method to compute the sum of the digits in an integer

0

Write a Java method to compute the sum of the digits in an integer

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..

import java.util.Scanner;
public class Javaexcercise {
 
  public static void main(String[] args)
    {
      Scanner in = new Scanner(System.in);
      System.out.print("Enter an integer: ");
      int digits = in.nextInt();
      System.out.println("The sum is Digit is: " + sumDigits(digits));
    }
 
 public static int sumDigits(long num) {
        int result = 0;
 
        while(num > 0) {
            result += num % 10;
            num /= 10;
        }
 
        return result;
    }
 
 }

Result:

Enter an integer: 123456

The sum is Digit is: 21

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Write a Java method to check whether an year (inte... >>
<< Write a Java method to count all vowels in a strin...