mbish75 - 2 months ago 32

Java Question

Hi very first Java class and it seems to be going a mile a minute. We learn the basics on a topic and we are asked to produce code for more advanced programs than what helped us get introduced to the topic.

Write a recursive program which takes an integer number as Input. The program takes each digit in the number and add them all together, repeating with the new sum until the result is a single digit.

Your Output should look like exactly this :

################### output example 1

Enter a number : 96374

I am calculating.....

Step 1 : 9 + 6 + 3 + 7 + 4 = 29

Step 2 : 2 + 9 = 11

Step 3 : 1 + 1 =2

Finally Single digit in 3 steps !!!!!

Your answer is 2.

I understand the math java uses to produce the output I want. I can do that much after learning the basics on recursion. But with just setting up the layout and format of the code I am lost. I get errors that make sense but have trouble correcting with my inexperience.

`package numout;`

import java.util.Scanner;

public class NumOut {

public static void main(String[] args) {

System.out.print("Enter number: ");

Scanner scan = new Scanner(System.in);

int n = scan.nextInt();

System.out.println(n);

}

public int sumDigit(int n){

int sum = n % 9;

if(sum == 0){

if(n > 0)

return 9;

}

return sum;

}

}

The output understandably duplicates the code given by the input from the user.

I had trouble calling the second class when I tried to split it up into two. I also know I am not soprln n, or the sum. So I try to make it into one and I can visibly see the problem but am unaware how to find the solution.

Answer

Think of recursion as solving a problem by breaking it into similar problems which are smaller. You also need to have a case where the problem is so small that the solution is obvious, or at least easily computed. For example, with your exercise to sum the digits of a number, you need to add the ones digit to the sum of all the other digits. Notice that `sum of all the other digits`

describes a smaller version of the same problem. In this case, the smallest problem will be one with only a single digit.

What this all means, is that you need to write a method `sumDigits(int num)`

that takes the ones digit of `num`

and adds it to the sum of the other digits by recursively calling `sumDigits()`

with a smaller number.