2016-01-06 45 views
0

我想知道为什么代码的顶层代码执行但代码的底部代码块没有。我所做的一切让对方执行了切换在我的if/else语句的条件位置Java在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!"); 
    } 
} 
+0

顶一个应该工作,底部将始终执行第一个if语句 – JRowan

+0

零不到99. –

+0

谢谢@JRowan你会碰巧知道它为什么会继续执行第一个if语句吗?如果不是,谢谢你,我会做更多的研究。 – RustyShackleford

回答

0

你的切换条件if (bottles <= 99)else if (bottles == 0)使第一块来执行,因为第一条件(瓶< = 99)是用于瓶子= 0真。

如果您希望在if声明之前执行else if,那么这绝不会发生。

也许你的情况应该是if (bottles > 0 && bottles <= 99),在这种情况下,如果瓶子= 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。

0

该问题与递归无关,但事实上“if”和“else”中的条件并不相互排斥。 只有只有安全地切换“if”和“else”的顺序,如果条件是排他性的。请记住,在if/elseif链中,只会执行第一个匹配条件。如果条件不相互排斥,则订单将很重要。

0

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

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