Creating an hourglass using asterisks

后端 未结 2 1120
情歌与酒
情歌与酒 2021-01-16 16:38

I would like to create an hourglass using the \"*\" character. For example if the user input was 5 then it would look like this:

*****
 ***
  *
 ***
*****
         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-16 17:18

    A complete solution in Java

    public static void draw(int w){
        draw(w, 0);
    }
    
    public static void draw(int W, int s){
        stars(W, s);
        if (W > 2) {
            draw(W-2, s+1);
            stars(W, s);
        }
    }
    public static void stars(int n, int s){
        if(s > 0){
            System.out.print(" ");
            stars(n, s-1);
        } else  if (n > 0){
            System.out.print("*");
            stars(n-1, s);
        } else {
            System.out.println();
        }
    }
    

    the parameter s was introduced to keep track of the number of spaces needed to center the asterisks Another way to do this would be have some global parameter to keep track of the total width and do subtraction but you seem to really like recursion.

    This code

    for(int i = 1; i < 7; i++){
        System.out.println("An hourglass of width " + i);
        draw(i);
        System.out.println();
    }
    

    Will now output this

    An hourglass of width 1
    *
    
    An hourglass of width 2
    **
    
    An hourglass of width 3
    ***
     *
    ***
    
    An hourglass of width 4
    ****
     **
    ****
    
    An hourglass of width 5
    *****
     ***
      *
     ***
    *****
    
    An hourglass of width 6
    ******
     ****
      **
     ****
    ******
    

提交回复
热议问题