2016-01-06 57 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爲真。這是一個無限的遞歸循環。