0
How do you create this figure for java? Using class constant
Write a method that will create the figure below. Add a class constant and change the constant to 7. 1 212 32123 4321234 543212345
1 Réponse
+ 2
My method could probably be optimised more, but this works via recursion:
/* note* this does not include the spaces for the pyramid shape, though you can just use a space in print for that. */
public class example{
final static int NUM_COLS = 7; // this is the class constant
static String rightSide(int nums){ /* rightSide includes 1 in this case */
if(nums == 0){
return ""; // done
}
return rightSide(nums-1)+nums;
}
static String leftSide(int nums, int max){ /* max is when to stop counting up */
if(nums == max)
return "";
return leftSide(nums+1, max)+nums;
}
public static void main(String[] args){
for(int i = 1; i <= NUM_COLS; i++){ // each col
System.out.println(); // new line
System.out.print(leftSide(2,i+1)+rightSide(i));
}
}
}