Answer:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("Sum of the digits in the number " + number + " is: " + sumDigits(number));
}
public static int sumDigits(int number){
int remainder = (int)Math.abs(number);
int sum = 0;
while(remainder != 0){
sum += (remainder % 10);
remainder = remainder / 10;
}
return sum;
}
}
Explanation:
- Initialize two variables to hold remainder and sum values
- Initialize a while loop operates while the remainder is not equal to zero
- Inside the loop, extract digits and assign these digits into sum. Remove extracted digits from the remainder
- When all the digits are extracted, return the sum value
- Inside main, get input from the user and call the method