If/Else语句中的Java递归

If/Else语句中的Java递归,java,if-statement,recursion,Java,If Statement,Recursion,我试图弄明白为什么顶部代码块执行,而底部代码块不执行。为了让另一个执行,我所做的只是在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 t

我试图弄明白为什么顶部代码块执行,而底部代码块不执行。为了让另一个执行,我所做的只是在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!");
    }
}
防火墙上的公共静态无效(int瓶){
如果(瓶==0){
System.out.println(“墙上没有啤酒,”
+“没有啤酒,你不能喝下一瓶,你不能传给别人。”
+“因为墙上已经没有啤酒了!”;
}else if(瓶子<代码>墙上的公共静态无效(内部瓶子){
如果(瓶==0){
System.out.println(“墙上没有啤酒瓶,”+“没有啤酒瓶,你不能把它拿下来,你不能把它传出去,”+“因为墙上没有啤酒瓶了!”);

}else-if(p问题与递归无关,而是“if”和“else”中的条件不是相互排斥的。
如果条件是互斥的,则只能安全地切换“if”和“else”的顺序。请记住,在if/elseif链中,只会执行第一个匹配条件。如果条件不是互斥的,则顺序很重要。

您的条件切换
if(瓶在第二种方法中,分支
瓶==0
将永远不会执行


因为当
瓶==0
时,
瓶顶部的一个应该可以工作,底部的一个将始终执行第一个if语句。如果零小于99,谢谢@JRowan,你会知道为什么它会继续执行第一个if语句吗?如果不是,无论如何谢谢你,我会做更多的研究。因为即使瓶是0,0也是W哦,非常感谢所有帮助我解决这个问题的人。
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);
            }
    }