java - 打印星号的 ASCII 菱形

标签 java shapes ascii-art

我的程序打印出这样的钻石:

...............*
..........*    *    *
.....*    *    *    *    *
*    *    *    *    *    *    *
.....*    *    *    *    *
..........*    *    *    
...............*

但只有当参数或菱形的每一边为 4 时,它才有效。例如,如果我输入 6,底部三角形的间距是错误的,我一直在尝试找出答案。

当参数改变时,底部的三角形不会改变,只有顶部的三角形会改变。它仅适用于输入 4

public static void printMoreStars(int n) {
    int rowsPrime = 0;

    for (int i = n + 1; i > 0; i--) {
        for (int j = 0; j < (2 * i) - 1; j++) {
            System.out.print(" ");
        }
        for (int d = 0; d < (2 * rowsPrime) - 1; d++) {
            System.out.print("*" + " ");
        }
        System.out.println(); //new line character

        rowsPrime += 1;
        System.out.println(" ");
    }

    //bottom triangle
    for (int i = 1; i < n + 1; i++) {
        for (int j = 0; j < (2 * i) + 1; j++) {
            System.out.print(" ");
        }
        for (int d = 0; d < rowsPrime; d++) {
            System.out.print("*" + " ");
        }
        System.out.println(); //new line character

        rowsPrime -= 2;
        System.out.println(" ");
    }
}

最佳答案

您在使用rowPrimes时犯了两个错误。请参阅下面我的注释:

public class Stars {
    public static void main(String[] args) {
        printMoreStars(Integer.parseInt(args[0]));
    }

    public static void printMoreStars(int n) {
        int rowsPrime = 0;

        for (int i = n + 1; i > 0; i--) {
            for (int j = 0; j < (2 * i) - 1; j++) {
                System.out.print(" ");
            }
            for (int d = 0; d < (2 * rowsPrime) - 1; d++) {
                System.out.print("*" + " ");
            }
            System.out.println();   //new line character

            rowsPrime += 1;
            System.out.println(" ");
        }

        rowsPrime -= 2; // <- middle line is already printed, so skip that

        //bottom triangle
        for (int i = 1; i < n + 1; i++) {
            for (int j = 0; j < (2 * i) + 1; j++) {
                System.out.print(" ");
            }
            for (int d = 0; d < (2 * rowsPrime) - 1; d++) { // <- changed condition to be the same as above
                System.out.print("*" + " ");
            }
            System.out.println();   //new line character

            rowsPrime--; // <- you have to decrease rowPrime by one.
            System.out.println(" ");
        }
    }
}

关于java - 打印星号的 ASCII 菱形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19109066/

相关文章:

java - 如何在消息框中显示变量的值?

java - 常见 IO - listFilesAndDirs 只显示文件

matlab - 在 MATLAB 中检测图像内部的圆形

Windows 批处理 : Can't echo ASCII art with . _|_

animation - 从 Haskell 输出 ascii 动画?

java - 尝试在不同的 JPanel 上重新绘制

java - 如何生成与 Jsoup 中特定元素匹配的 XPath 查询?

Android:将图像添加到具有形状背景的按钮

android - 无法在样式中设置资源形状的高度和宽度