首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用递归Java镜像三角形

使用递归Java镜像三角形
EN

Stack Overflow用户
提问于 2018-10-07 04:56:23
回答 1查看 235关注 0票数 1

我需要在java中制作镜像三角形的帮助,就像问题中的:Creating a double mirrored triangle。然而,它需要使用递归来完成。我已经想出了如何制作两个版本的三角形:

*

**

**

*

但我想不出其他的路线。这部分作业没有评分,这是为了帮助我们理解,这样我们就可以弄清楚如何做镜像图像。

代码语言:javascript
复制
public static String triangle(int size) {
    if (size == 0)
        return "";

    String dots = triangle(size - 1);
    dots = dots + ".";
    System.out.println(dots);

    return dots;
}

//right alignment- small to big
public static String triangle2(int size) {
    if (size == 0)
        return "";

    String dots = "";
    for (int i = 0; i < size; i++){
        dots = dots + ".";
    }


    System.out.println(dots);
    return dots + triangle2(size - 1);

}
public static String triangle3(int size) {
    if (size == 0)
        return "";    

    String spaces = "";
    for (int i=0; i < size-1; i++){
        spaces = spaces + " ";
    }


    String dots = "";
    dots = dots + ".";

    System.out.println(spaces + dots);
    return spaces + dots + triangle3(size-1);

}
EN

回答 1

Stack Overflow用户

发布于 2018-10-07 06:17:17

这里有一个解决方案,使用两种不同的递归方法:

代码语言:javascript
复制
public static void printMirrorTriangle(int size) {
    printRow(1, size);
}
private static void printRow(int row, int size) {
    System.out.println(repeat('*', row) + repeat(' ', (size - row) * 2) + repeat('*', row));
    if (row < size)
        printRow(row + 1, size);
}
private static String repeat(char c, int count) {
    return (count == 0 ? "" : c + repeat(c, count - 1));
}

测试

代码语言:javascript
复制
printMirrorTriangle(4);

输出

代码语言:javascript
复制
*      *
**    **
***  ***
********
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52683273

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档