# very frustrating.. recursive

• 01-06-2011, 03:54 PM
Yakg
very frustrating.. recursive
Hi, in this example I'm trying to return a string unsuccessfully.
The input number is 3000 and the output should be MMM, I completely don't understand where I go wrong with this recursive method...

--------------------------------------------------------------------------
public static String num2rom (int a){
String m = "M";

if (a == 0) {
return "";
} else {
if (a >=1000){
}
return helper ("M",a-1000);
}
}

public static String helper (String thou, int a){
String result = "";
result+=thou;
return num2rom (a);
}

}

//thanks
• 01-06-2011, 03:58 PM
goldest
What happens when you run it? Whats the output? Or error?

Goldest
• 01-06-2011, 04:03 PM
Tolls
Code:

```public static String helper (String thou, int a){     String result = "";     result+=thou;     return num2rom (a); }```
You create result, append thou to it and then...do nothing with it.
It vanishes.
• 01-06-2011, 05:26 PM
hosscomp
Code:

```} else { if (a >=1000){ }```
Useless IF block
• 01-06-2011, 11:09 PM
sunde887
Im a little unfamiliar with java, but I have a good understanding of recursion.
The problem I see is that you only really need one function.

Have it take an int amount, if it's less than 1000 it can return the result.

If you want me to print actual working code I will, just let me know.

But do this for me, try making one function, which takes a string and a number.

this should be the template of recursion
Code:

```recursive code(args) if it meets a termination condition, end and return the answer. else make some change and reapply the function```
• 01-06-2011, 11:25 PM
sunde887
Also, if you are somewhat new with the idea of recursion, I find the book, HTDP does a very good job of teaching recursion. I'd say 75% of the exercises in the book are recursion based.

It's free online at htdp.org, very easy to understand, and I think it's very well written. It uses Dr.racket programming language which is quite different than java and c/c++ but it's nice to get a good understanding if you are a beginner.