如何使用嵌套 for 循环制作钻石

新手上路,请多包涵

所以我被指派用 Java 制作一颗带星号的钻石,我真的很困惑。到目前为止,这是我想出的:

 public class Lab1 {
    public static void main(String[] args) {
        for (int i = 5; i > -5; i--) {
            for (int j = 0; j < i; j++) {
                System.out.print(" ");
            }
            for (int j = 0; j >= i; j--) {
                System.out.print(" ");
            }
            System.out.println("*");
        }
    }
}

输出

原文由 Anshul Desai 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 486
1 个回答

为了制作钻石,您需要设置空间和星星的形状。因为我是初学者,所以我只使用嵌套循环制作了这个简单的程序。

 public class Diamond {
    public static void main(String[] args) {
        int size = 9,odd = 1, nos = size/2; // nos =number of spaces
        for (int i = 1; i <= size; i++) { // for number of rows i.e n rows
            for (int k = nos; k >= 1; k--) { // for number of spaces i.e
                                                // 3,2,1,0,1,2,3 and so on
                System.out.print(" ");
            }
            for (int j = 1; j <= odd; j++) { // for number of columns i.e
                                                // 1,3,5,7,5,3,1
                System.out.print("*");
            }
            System.out.println();
            if (i < size/2+1) {
                odd += 2; // columns increasing till center row
                nos -= 1; // spaces decreasing till center row
            } else {
                odd -= 2; // columns decreasing
                nos += 1; // spaces increasing

            }
        }
    }
}

如您所见 nos 是空格数。它需要减少到中心行,并且需要增加星星的数量,但在中心行之后则相反,即空间增加而星星减少。

size 可以是任何数字。我在这里将它设置为 9,所以我将有一个大小为 9 的星,最大为 9 行和 9 列…空间数量 ( nos ) 将是 9/2 = 4.5 。但是 java 会将其作为 4,因为 int 不能存储十进制数,并且中心行将是 9/2 + 1 = 5.5 ,这将导致 5 为 int

所以首先你要排… 9 排

(int i=1;i<=size;i++) //size=9

然后像我一样打印空格

(int k =nos; k>=1; k--) //nos being size/2

然后终于星星

(int j=1; j<= odd;j++)

一旦线路结束…

您可以使用 if 条件调整星号和空格。

原文由 Alok 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题