Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Programming Recursion Help- Download DigitPlay.java . Complete the numDigit

ID: 3803219 • Letter: J

Question

Java Programming Recursion Help-

Download DigitPlay.java. Complete the numDigits method which does the same thing as the in-class example and run the program. For example, input 3278 will generate output 4; 32780 should generate output 5. Also try a negative number.

Now add another method sumDigits, which sums those digits in the input positive integer. For example, input 321 will generate output 6 since 3+2+1 = 6. Define this method in the recursive way too. You can modify numDigits easily to get sumDigits!

Be reminded that sumDigits should be static too, so it can be invoked directly in the main method without creating an object. Add code to main() to test your method.

Thank you!

Explanation / Answer

// DigitPlay.java
import java.util.Scanner;

public class DigitPlay
{
/*
returns the number of digits in n
*/
public static int numDigits(int n)
{
// base case
if(n < 10)
return 1;
// recusive case
else
return 1+numDigits(n/10);

}

/*
returns the sum of digits in n
*/
public static int sumDigits(int n)
{
if(numDigits(n) == 1)
return n;
// recusive case
else
return n%10+sumDigits(n/10);

}

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 numDigits in the number
// Print the number returned from numDigits
System.out.println (" The number " + num + " contains "+ numDigits (num) + " numDigits.");
System.out.println ();
System.out.println ("Sum of digits of " + num + " is " + sumDigits(num));
System.out.println ();
}
}

}

/*
output:

Please enter a positive integer: 32780

The number 32780 contains 5 numDigits.

Sum of digits of 32780 is 20

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote