public String starString(int n){
int m = (int)Math.pow(2,n);
String str="";
str = starString(m-1,str);
return str;
}
private String starString(int n, String str){
String temp ="";
if (n<0) {
try{
throw new IllegalArgumentException();
}
catch(IllegalArgumentException ex){
}
}
else {
temp+=("*");
starString(n-1,str);
}
return temp;
}
Can someone please explain to me why this code returns a single asterisk even if its called by a value greater than n >= 0?
I debugged and noticed that after throwing the exception it recurses again and all the asterisks get chopped to “”. I’ve tried it many times. Its also required that you should throw the IllegalArgumentException if n < 0.
In Java strings are immuntable, hence you need to assign a new value to
temp(and passtempas the parameter):Additionally you’d need to assign
strtotemp, otherwise each recursion would just return a single asterisk:A much simpler, cleaner (and correct) version of your recursive method would look like this:
Note that you don’t even need to pass the string as a parameter. Also note that recursion is overkill here, using a loop would make much nore sense. Also note that string concatenation is costly and gets slow quickly for higher values of
n(due to immutable string instances being created over and over again). In that case you’d better useStringBuilder:On my machine a loop version using string concatenation takes around 12 seconds for n = 100000 whereas the
StringBuilderversion takes 0.007 seconds.