Write a Java program in which a method named digitSum that a
Write a Java program in which a method named digitSum that accepts an integer as a parameter and returns the sum of the digits of that number. For example, the call digitSum(29107) returns 2+9+1+0+7 or 19. For negative numbers, return the same value that would result if the number were positive. For example, digitSum(-456) returns 4+5+6 or 15.The call digitSum(0) returns 0
Solution
DigitSumTest.java
import java.util.Scanner;
public class DigitSumTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(\"Enter an integer: \");
int n = scan.nextInt();
int sum = digitSum(n);
System.out.println(\"The sum of digits is \"+sum);
}
public static int digitSum (int n) {
int sum = 0;
if(n == 0){
return 0;
}
else if(n < 0){
n = -n;
}
do {
sum += n % 10;
} while ((n = n / 10) != 0);
return sum;
}
}
Output:
Enter an integer: -456
The sum of digits is 15
Enter an integer: 29107
The sum of digits is 19
