首页 > 解决方案 > 在同一行上打印形状

问题描述

我正在尝试在同一行上打印一个正方形和一个三角形,如下所示:

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

我已经创建了单独制作它们的功能

public static void drawTriangle(int n) {
    int k = 2 * n - 5;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < k; j++) {
            System.out.print(" ");
        }
        k = k - 1;
        for (int j = 0; j <= i; j++) {
            System.out.print("* ");
        }
        System.out.println();
    }
}

public static void drawSquare(int width, int height) {
    for (int i = 0; i < height; i++) {
        System.out.print("* ");
    }
    System.out.println();
    for (int i = 0; i < width - 2; i++) {
        System.out.print("* ");
        for (int j = 0; j < height - 2; j++) {
            System.out.print("* ");
        }
        System.out.println("* ");
    }
    for (int i = 0; i < height; i++) {
        System.out.print("* ");
    }
    System.out.println();
}

但我不知道如何将两个输出组合在同一行。

标签: javaloopsshapes

解决方案


解决方案

最简单的解决方案是将两种方法合二为一,如下所示:

public static void drawTriangleAndSquare(int widthS, int heightS) {
    // number of leading spaces in front of triangle
    int k = 2 * heightS - 5;

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

        // print triangle
        System.out.print("\t");
        for (int j = 0; j < k; j++) {
            System.out.print(" ");
        }

        k--;

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

        System.out.println();
    }
}

public static void main(String[] args) {
    drawTriangleAndSquare(5, 4);
}

输出

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

请注意,我已经稍微清理了您的代码,尤其是drawSquare()函数。


局限性

我的实现只允许您打印相同高度的正方形和三角形(它们都依赖于 中的变量heightSdrawTriangleAndSquare()

PS如果你想在三角形和正方形之间有更多的空白,只需添加更多\t的 s at System.out.print("\t")


推荐阅读