# Thread: very frustrating.. recursive

1. Member
Join Date
Dec 2010
Posts
63
Rep Power
0

## 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

2. What happens when you run it? Whats the output? Or error?

Goldest

3. Moderator
Join Date
Apr 2009
Posts
13,367
Rep Power
24
Java 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.

4. Member
Join Date
Oct 2010
Posts
63
Rep Power
0
Java Code:
} else {
if (a >=1000){
}
Useless IF block

5. 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
Java Code:
recursive code(args)
if it meets a termination condition, end and return the answer.
else make some change and reapply the function

6. 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.
Last edited by sunde887; 01-06-2011 at 11:30 PM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•