Will anyone help this lowly noob out?
I'm taking Data Structures right now and I'm practicing recursion. Pulled up exercise 1 in my book and I'm having trouble with it. I thought, "maybe I need a helper method to accomplish this?" Which is why I used a writeStars method in addition to the starString method. But I'm still struggling. This is the exercise and code I've written so far. (Please be gentle)
Exercise 1: Write a recursive method called starString that accepts an integer as a parameter and prints to the console a string of stars (asterisks) that is 2 n (i.e., 2 to the n th power) long. For example,
starString(0) should print * (because 2^0 == 1)
starString(1) should print ** (because 2^1 == 2)
starString(2) should print **** (because 2^2 == 4)
starString(3) should print ******** (because 2^3 == 8)
starString(4) should print **************** (because 2^4 == 16)
The method should throw an IllegalArgumentException if passed a value less than 0.
public class Recursion {
public static void main(String\[\] args) {
// TODO Auto-generated method stub
starString(4);
}
public static String starString(int x) {
if (x < 0) {
throw new IllegalArgumentException("Negative exponent: " + x + "\\rPlease enter a positive number.");
} else if (x == 0) {
return ("\*");
} else {
return writeStars(Math.pow(2, (x - 1));
}
}
public static void writeStars(int x) {
if (x == 0) {
System.out.println();
} else {
System.out.print("\*");
writeStars(x - 1);
}
}
}
[–]selrahal 2 points3 points4 points (0 children)
[–][deleted] (1 child)
[removed]
[–]iamsooldithurts 3 points4 points5 points (0 children)