use*_*963 2 java recursion infinite-loop
我正在整理一个代码来输出以下模式:
000000000X
00000000XX
0000000XXX
000000XXXX
00000XXXXX
0000XXXXXX
000XXXXXXX
00XXXXXXXX
0XXXXXXXXX
Run Code Online (Sandbox Code Playgroud)
(每行应该是一个接一个.我不太确定如何在论坛上显示模式...对不起)
我应该在代码中使用递归循环,但我最终在一个无限循环中,我真的不明白为什么..(可能可以确定我从来没有实际使用过递归循环.)是我的代码:
class Recursion {
//recursion should stop after 9 attempts
static int stopindex = 9;
public static void main(String[] args) {
//a=number of "O"s and b=number of "X"s
int a = 9;
int b = 1;
recursion(a, b);
}
public static void recursion(int a, int b) {
//start of recursion at index 1
int startindex = 1;
//stop condition of recursion
if (startindex == stopindex)
return;
//printing of pattern
for (int i = a; i > 0; i--) {
System.out.print("O");
}
for (int j = 0; j < b; j++) {
System.out.print("X");
}
System.out.println();
--a;
++b;
++startindex;
recursion(a, b);
}
}
Run Code Online (Sandbox Code Playgroud)
你的算法略有偏差,你不应该有静态变量,你不应该改变a,你的第一个for循环条件 - 我想你想要的,
public static void recursion(int a, int b) {
// stop condition of recursion
if (a == b) return;
// printing of pattern
for (int i = a - b; i > 0; i--) {
System.out.print("O");
}
for (int j = 0; j < b; j++) {
System.out.print("X");
}
System.out.println();
// --a;
++b; // <-- this could be done in the recursion call below,
recursion(a, b);
// recursion(a, ++b); // <-- like that.
}
Run Code Online (Sandbox Code Playgroud)
输出是
OOOOOOOOX
OOOOOOOXX
OOOOOOXXX
OOOOOXXXX
OOOOXXXXX
OOOXXXXXX
OOXXXXXXX
OXXXXXXXX
Run Code Online (Sandbox Code Playgroud)