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

Introduction

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

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

Leave a Comment

x