使用星号创建沙漏 [英] Creating an hourglass using asterisks

查看:97
本文介绍了使用星号创建沙漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用*字符创建沙漏。例如,如果用户输入为5,那么它将如下所示:

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

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

和3看起来像这样:

 ***
  *
 ***

到目前为止,我有:

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

它会创建

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






推荐答案

Java中的完整解决方案

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();
    }
}

引入参数s以跟踪数字星号中心所需的空间
另一种方法是使用一些全局参数来跟踪总宽度并进行减法,但你似乎非常喜欢递归。

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.

此代码

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

现在输出这个

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
******
 ****
  **
 ****
******

这篇关于使用星号创建沙漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆