I need to print a triangle and its inverted triangle (standing on its tip). I manage to print out only the triangle. I know I can easily use for loop but I want to know how to make use recursion and in my case, I don't know how to print the both triangle and the inverted one.Thank you.
Example desired output:
*
**
***
****
****
***
**
*
My code:
public class Recursion1 {
public static void main(String[] args) {
Recursion1 me = new Recursion1();
me.doIt();
}
public void doIt() {
nums(4);
}
public String nums(int counts) {
if (counts <= 0) {
return "";
}
String p = nums(counts - 1);
p = p +"*";
System.out.print(p);
System.out.println();
return p;
}
}
My result:
Results:
*
**
***
****
解决方案
You have to rethink the problem, this could be a possible solution:
public class Recursion1 {
private static int endValue;
private static int startValue = 1 ;
public Recursion1(int endValue){
Recursion1.endValue = endValue;
}
public static void main(String[] args) {
Recursion1 me = new Recursion1(4);
me.doIt();
}
public void doIt() {
nums("*");
}
public String nums(String value) {
if( startValue == endValue){
System.out.println(value);
}else{
System.out.println(value);
startValue ++;
value = value.concat("*");
nums(value);
value = value.substring(1);
System.out.println(value);
}
return value;
}}