Write a method called digitSum that accepts an integer as a parameter and return
ID: 3557297 • Letter: W
Question
Write a method called 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.
Call the digitSum() method from a main program that allows the user to input an integer and then
prints out the sum of the digits. The program will always process at least one integer. After each
integer is processed, ask the user if he or she wants to process another integer.
Explanation / Answer
class DigitSum { public static void main(String args[]) { int i,a=0, sum=0; i=Integer.parseInt(args[0]); //taking integer from command line while(i!=0) { a=i%10; i=i/10; sum=sum+a; } System.out.println(sum); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.