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 <em>remainder</em> and <em>sum</em> values
- Initialize a while loop operates while the <em>remainder</em> is not equal to zero
- <u>Inside the loop</u>, extract digits and assign these digits into <em>sum</em>. Remove extracted digits from the <em>remainder</em>
- When all the digits are extracted, return the <em>sum</em> value
- Inside main, get input from the user and call the method