我正在尝试获得如下所示的输出:
3
2
1
“重启”
1
2
3
:递归使用此代码。:
public static void restart(int n){
return; //fill in here
}
public static void restart(int n){
if (n == 0) {
System.out.println("\"restart\"");
return;
}
System.out.println(n);
restart(n-1);
System.out.println(n);
}
应该这样做。
编写递归方法需要回答以下两个问题:
递归什么时候停止?(更正式地说,基本情况是什么?)
递归将如何继续?
请注意,递归延续可能有多种情况。
public static void restart(int n){
if (n == 0) {
System.out.println("\"restart\"");
restart(3)
return;
}
System.out.println(n);
restart(n-1);
}
这将继续打印
3
2
1
"restart"
1
2
3
.............
我想这就是你想要的。
public class statik
{
static int countDown=3;static boolean down=true;
static void downward(int c,boolean down)
{
if(c!=0)
{
System.out.println(c);
}
else
{
System.out.println("Restart");
}
if(down)
{
c--;
}
else
{
c++;
}
if(c<1)
{
down=!down;
}
if(c>countDown)System.exit(0);
downward(c,down);
}
public static void main(String[] args)
{
downward(countDown,down);
}
}
输出:
3
2
1
Restart
1
2
3
我相信你正在寻找
public static void restart(int n) {
System.out.println(n);
if (n == 1)
System.out.println("restart");
else
restart(n-1);
System.out.println(n);
}
带有一些附加信息的版本
public static void restart(int n) {
//lets pring numbers first
System.out.println(n); // <-------------------------------------+
// |
if (n == 1) // |
//then after number 1 lets pring "restart" // |
System.out.println("restart"); // |
else // |
//if n is not 1 we continue recursion with lower number // |
restart(n-1); // -------------------------------------------+
//after we stopped creating new recursive calls (when n==1) its time to print
//rest of numbers
System.out.println(n); //I used n-1 instead of --n earlier so I can use n here
}