【问题标题】:Calling Methods to Generate ASCII Art调用方法生成 ASCII 艺术
【发布时间】:2018-03-12 02:09:00
【问题描述】:

对于阅读本文的任何人,我感谢您抽出宝贵的时间这样做。

基本上我试图生成这种精确的 ASCII 艺术通过调用 x 数量的方法,我个人在考虑 3 个

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

第一个生成上半部分,第二个生成中间部分,第三个生成星号的最后部分。

我目前以单一方法处理绘图,我需要帮助将其分解为多个部分。

https://pastebin.com/RDE2KLHk

这个 paste-bin 链接有我当前的进度。

谢谢。我非常感激。

【问题讨论】:

    标签: java loops methods


    【解决方案1】:

    你了解过参数吗?基本上,您有一个方法可以调用来绘制整个图像。图像可以分为两部分,上半部分和下半部分。您不需要中间部分,因为它可以覆盖在上半部分或下半部分的循环中。如果您想要一种方法来绘制中间,您可以自己编写并调整 for 循环。

    public static void main(String[] args) {
        // pass in the height of the triangles
        // in your example it's 6
        printImage(6);
    }
    
    public static void printImage(int height) {
        printTop(height);
        printBottom(height);
    }
    
    //also draws the middle part
    public static void printBottom(int height) {
        for (int i = height; i > 0; i--) {
            printStar(i);
            printSpace(2 * (height - i));
            printStar(i);
            System.out.println();
        }
    }
    
    public static void printTop(int height) {
        for (int i = 1; i < height; i++) {
            printStar(i);
            printSpace(2 * (height - i));
            printStar(i);
            System.out.println();
        }
    }
    
    public static void printStar(int stars) {
        for (int i = 0; i < stars; i++) {
            System.out.print("*");
        }
    }
    
    public static void printSpace(int spaces) {
        for (int i = 0; i < spaces; i++) {
            System.out.print(" ");
        }
    }
    

    您的方法也可以采用多个参数。请注意 printTop 和 printBottom 的代码基本相同。这是不好的。为了减少冗余,我们可以写另一种方法。

    public static void printLine(int stars, int spaces) {
        printStar(i);
        printSpace(spaces);
        printSTar(i);
    }
    

    然后,在 printTop 和 printBottom 方法中,你可以这样调用它:

    printLine(i, 2 * (height - i));
    

    【讨论】:

    • 非常感谢。我会更多地研究方法和参数!
    • @MathewRomano 我实际上只是按照您在问题中的要求对其进行了编辑以绘制顶部和底部 :)
    猜你喜欢
    • 2011-03-27
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多