我需要帮助编写一个程序,使用嵌套循环在一行上打印出两个形状 [英] I need help writing a program that prints out two shapes on one line using nested loops

查看:235
本文介绍了我需要帮助编写一个程序,使用嵌套循环在一行上打印出两个形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些形状应该是什么样的喜欢

Here is what the shapes should look like :

这是我到目前为止的代码:

Here is my code so far:

public class Diamonds {

    public static void main(String[] args) {
        for (int i = 1; i < 10; i += 2) {
            for (int j = 0; j < 9 - i / 2; j++) {
                System.out.print(" ");
            }

            for (int j = 0; j < i; j++) {
                System.out.print("*");
            }

            System.out.print("\n");
        }

        for (int i = 7; i > 0; i -= 2) {
            for (int j = 0; j < 9 - i / 2; j++) {
                System.out.print(" ");
            }

            for (int j = 0; j < i; j++) {
                System.out.print("*");
            }

            System.out.print("\n");
        }
    }
}

我无法获得第二个形状

推荐答案

为了不破坏这个问题的乐趣,我将在不编写任何代码的情况下解释你需要做什么。

In order to not spoil your fun with this problem, I will explain what you need to do without writing any code.

要获得第二个形状,你需要在每个中添加两个嵌套的 for 循环你已经拥有的两个外部循环。

To get the second shape in there, you would need to add two additional nested for loops into each of the two "outer" loops that you already have.

第三个循环将产生固定数量的空格。请注意,第一个形状的右边缘和第二个形状的左边缘之间的距离是恒定的,因此第三个循环将很容易编码。

Loops number three will produce a fixed number of spaces. Note that the distance between the right edge of the first shape and the left edge of the second shape is constant, so your third loops will be easy to code up.

循环第四个循环将像第一个循环一样循环,但它们会改变位置:第一个外循环的第一个内循环将是第二个外循环中的第四个内循环,反之亦然。

Loops number four will loop like your first loop, but they would change places: the first inner loop from the first outer loop will be the forth inner loop in the second outer loop, and vice versa.

这篇关于我需要帮助编写一个程序,使用嵌套循环在一行上打印出两个形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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