Reputation: 616
I'm having trouble with a recursive method that will return and print in my main method the numbers from X (X being a int on commandline) to 0. Returning the numbers as a String.
For example my commandline argument is 4. My output should be: 4, 3, 2, 1, 0
I kind of understand how to reverse a string like: "123" to "321".. But no clue when getting a integer like 3, and returning it like "3, 2, 1, 0" as a string. :o
My code atm:
public static void main(String[] commandlineArguments) {
if (commandlineArguments.length == 0) {
System.out.println("Please enter a least one commandline!");
}
else {
Integer number = new Integer(0); // initialize number
try {
number = Integer.parseInt(commandlineArguments[0]);
}
catch (NumberFormatException exception) { // NumberFormatException
System.out.println(exception + " is not a integer!");
System.exit(1); // end program
}
String reverse = reverse1(number);
System.out.println(reverse);
}
}
public static String reverse1(Integer number){
if (number == 0){
return "";
}
else{
return "";
}
}
}
Upvotes: 0
Views: 156
Reputation: 893
public static String reverse1(int number){
if (number == 1){
return "1";
} else {
return number + ", " + reverse1(number - 1);
}
}
The trick with recursion is - in my opinion - always to search the trivial case. So here the easiest input is 1 and the result would be "1"
reverse1(1) = "1";
And then you need that "strange" recursion step where you reduce your input towards that trivial case.
reverse1(n) = n, reverse(n-1)
Here you just say:
The result of a number n is always the result of "this number minus 1" with that extra number n in front.
Think about it, its quite logical.
It's sometimes not easy to think of a problem in that "recursive way". But often it makes things alot easier.
Upvotes: 5
Reputation: 18848
public static void main(String[] commandlineArguments) {
printNumber(number);
}
public static String printNumber(Integer number){
if (number == 0){
return "0";
}
return number +" " + printNumber(number-1);
}
Upvotes: 2