If / Else语句中的Java递归

时间:2016-01-06 02:18:58

标签: java if-statement recursion

我正在试图弄清楚为什么Code的顶部块会执行但底部的代码块却没有。我所做的就是让对方执行是在if / else语句中切换条件位置

public static void onTheWall(int bottles){
    if (bottles == 0){
        System.out.println("No bottles of beer on the wall,"
                           + " no bottles of beer, ya’ can’t take one down, ya’ can’t pass it around," 
                           + "cause there are no more bottles of beer on the wall!");
    } else if (bottles <= 99){
        System.out.println(bottles + " bottles of beer on the wall, " 
                           + bottles + " bottles of beer, ya’ take one"
                           + " down, ya’ pass it around, " 
                           + (bottles - 1) + " bottles of beer on the wall");
        onTheWall(bottles-1);
    }
}

public static void onTheWall(int bottles){
    if (bottles <= 99){
        System.out.println(bottles + " bottles of beer on the wall, " 
                           + bottles + " bottles of beer, ya’ take one"
                           + " down, ya’ pass it around, " + (bottles - 1) 
                           + " bottles of beer on the wall");
        onTheWall(bottles-1);
    } else if (bottles == 0){
        System.out.println("No bottles of beer on the wall," 
                           + " no bottles of beer, ya’ can’t take one down, ya’ can’t pass it around," 
                           + "cause there are no more bottles of beer on the wall!");
    }
}

4 个答案:

答案 0 :(得分:0)

public static void onTheWall(int bottles){
         if (bottles == 0){
                System.out.println("No bottles of beer on the wall," + " no bottles of beer, ya’ can’t take one down, ya’ can’t pass it around," + "cause there are no more bottles of beer on the wall!");
            } else if (bottles <= 99){
                System.out.println(bottles + " bottles of beer on the wall, " + bottles + " bottles of beer, ya’ take one"
                + " down, ya’ pass it around, " + (bottles - 1) + " bottles of beer on the wall");
            onTheWall(bottles-1);
            }
    }

您的递归调用不会发生,因为在开始时瓶子是0.尝试移动递归调用的位置或将elseif更改为if。

答案 1 :(得分:0)

问题与递归无关,但事实上&#34; if&#34;和#34;其他&#34;不是相互排斥的。 您只能 安全地切换&#34;的顺序,如果&#34;和#34;其他&#34;如果条件是独家的。请记住,在if / elseif链中,只会执行第一个匹配条件。如果条件不相互排斥,则订单将很重要。

答案 2 :(得分:0)

您切换条件if (bottles <= 99)else if (bottles == 0)会导致第一个块执行,因为瓶子= 0时第一个条件(瓶子<= 99)为真。

如果您希望else ifif语句之前执行,那么这种情况永远不会发生。

也许你的情况应该是类似if (bottles > 0 && bottles <= 99)的情况,在这种情况下,如果瓶子= 0,你的第二个区块将会执行。

答案 3 :(得分:0)

在第二种方法中,分支bottles == 0将永远不会执行。

因为bottles == 0bottles <= 99为真。它是一个无限的递归循环。