【发布时间】:2021-04-12 13:30:30
【问题描述】:
我正在尝试通过递归在 java 中构建一个简单的棋盘布局,但我的问题是,在每个递归调用中,字段的数量都会减少一个,这是错误的。黑色字段用“#”表示,白色字段用空格表示。我已经用迭代完成了,这没问题,但递归方法让我很头疼。
import java.util.Scanner;
public class Chess {
public static int chess(int boardlength) {
if (boardlength == 0) {
return boardlength;
} else {
pattern(boardlength);
System.out.println("\n");
}
return chess(boardlength - 1);
}
public static int pattern(int runs) {
if (runs == 0) {
return runs;
} else {
if (runs % 2 != 0) {
System.out.print("#");
} else {
System.out.print(" ");
}
}
return pattern(runs - 1);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Length of the board: ");
int boardlength = input.nextInt();
chess(boardlength);
}
}
【问题讨论】:
-
你必须使用递归吗?在我看来,使用简单的循环结构会更容易。
-
不幸的是,是的。我已经通过嵌套的 for 循环进行了电路板布局,这非常容易和简单,但是将其转换为递归非常困难,至少对我来说是这样
标签: java loops recursion chess