I'm supposed to write a recursive method to count the sum of the digits in an integer. For example, 431 should return 8 (4 + 3 + 1).

The method in question is sumDigits()

As the code is now, it adds a digit to what is returned each time it adds something

so for 431 it returns 478 - the 7 is from (4 + 3) and the 8 is from (4 + 3 + 1)

I know it's something simple, but for the life of me I can't figure out what I'm doing wrong. Any help would be appreciated.

Here's the method that needs work:

Code:

[B] public static int sumDigits(int num)
{
if (num < 10)
return (num);
else
return (num + sumDigits(num / 10));
}[/B]

And here's the whole program:

Code:

import java.util.Scanner;
public class DigitPlay
{
public static void main (String[] args)
{
int num; //a number
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.print ("Please enter a positive integer: ");
num = scan.nextInt ();
if (num <= 0)
System.out.println ( num + " isn't positive -- start over!!");
else
{
// Call numDigits to find the number of digits in the number
// Print the number returned from numDigits
System.out.println ("\nThe number " + num + " contains " +
+ numDigits(num) + " digits.");
System.out.println("The sum of the digits in " + num + " is " +
sumDigits(num) + ".");
System.out.println ();
}
}
// -----------------------------------------------------------
// Recursively counts the digits in a positive integer
// -----------------------------------------------------------
public static int numDigits(int num)
{
if (num < 10)
return (1);
else
return (1 + numDigits(num/10));
}
// recursively count the sum of the digits in a positive integer
[B] public static int sumDigits(int num)
{
if (num < 10)
return (num);
else
return (num + sumDigits(num / 10));
}[/B]
}