gpt4 book ai didi

java - 仅使用递归打印 V 形

转载 作者:行者123 更新时间:2023-12-02 08:52:41 29 4
gpt4 key购买 nike

我正在尝试仅使用递归打印出字母 V 的形状。我在这个网站上看到了一些与我的问题相关的代码,但大多数使用循环而不是递归。

这是我的代码:

  public class Pattern {

public static void main(String[] args) {
printPattern(5);
}
public static void Pattern(int count, String s) {
if (count == 0) {
return;
}

System.out.print(s);
Pattern(count - 1, s);
}

public static void upperhalf(int count, int max) {
if (count == 0) {
return;
}

Pattern(max - count, " ");
Pattern(count, "* ");

System.out.println();

upperhalf(count - 1, max);
}



public static void printPattern(int n) {
upperhalf(n, n);

}
}

输出:

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

我想要的输出:

  *       *
* *
* *
* *
*

最佳答案

解决这个问题的一种方法。将两次连续的 Pattern 调用替换为:

    Pattern(max - count, " ");
Pattern(1, "* ");
Pattern(count - 2, " ");
Pattern(1, count > 1 ? "* " : "");

(即您的第一个 Pattern 调用,然后是单个 * 的显式调用,然后是几个空格(比您的方法中少 2 个),然后是最后一个 *)。

您还需要稍微更改退出语句:

public static void Pattern(int count, String s) {
if (count <= 0) { // <= instead of ==
return;
}

关于java - 仅使用递归打印 V 形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60683904/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com