java - 仅使用递归打印 V 形
问题描述
我正在尝试仅使用递归打印出字母 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(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;
}
推荐阅读
- flutter - 无法弄清楚如何正确设置 DropdownButton 的样式
- java - 如何从给定的 Instant 获取第二天结束的日期时间?(爪哇)
- c# - C# 传递一个带有可选默认值的整数变量
- javascript - 如果我使用 pre-2015 方法在函数内声明参数默认值,则 QuickSort 无限循环,但如果我使用 ES2015 默认参数值,则工作正常
- angular-ui-grid - ui-grid columnDefs :如何将单元格内容转换为用户友好和数据函数的某个值?
- regex - Microsoft Word 正则表达式:是否有“或”运算符,例如 |?
- python - UnicodeEncodeError:“charmap”编解码器无法在位置 47 编码字符“\x9f”:字符映射到
- python - pyspellchecker:不拆分 URL
- javascript - 在 Node.js 中退出 CRTL-D 上的 CLI
- c# - 测试流的 FTP 输出