2016-09-04 46 views
-2
public class Shuffle1 { 
    public static void main(String[] args) { 
     int x = 3; 

     if(x > 2) { 
      System.out.print("a"); 
     } 

     while(x > 0) { 
      x = x - 1; 
      System.out.print("-"); 
     } 

     if(x == 2) { 
      System.out.print("b c"); 
     } 

     if(x == 1) { 
      System.out.print("d"); 
      x = x - 1; 
     } 
    } 
} 

我正在學習一本名爲「Head First Java」的書中的Java,並且我正按照本書中的建議使用TextEdit。我應該能夠編譯代碼以獲得a-b c-d的答案,但是每次編譯它時,我都會得到一個---的結果。我已經徹底檢查過自己,如果有人能幫助我,我會很感激。 Here is the original question from the book.循環和如果語句不給所需的輸出

+1

我認爲第二個和第三個if語句應該放在while循環中。 – markspace

+0

這是在調試器中單步執行代碼的地方,可以真正幫助您調試程序。它還將幫助您通過練習來逐步完成頭腦中的代碼。 –

回答

1

所以,如果x是3,我帶你去通過會發生什麼:

  1. 打印的出 「一」,因爲3> 2
  2. 值減x爲0,打印 「 - 」 上方式,因爲它需要2減量來滿足休息條件,x> 0

這意味着它會正確打印a--。爲了實現a-b c-d,你必須在if語句循環,就像這樣:

while(x > 0) { 
    x = x - 1; 
    System.out.print("-"); 

    if(x == 2) { 
     System.out.print("b c"); 
    } 

    if(x == 1) { 
     System.out.print("d"); 
     x = x - 1; 
    } 
} 

現在執行週期是:

  1. x> 2,所以打印 「一」
  2. 去進入循環
  3. x變爲2
  4. 打印「 - 」
  5. x是2,所以打印 「BC」
  6. 繼續迭代
  7. 下一次迭代,x變爲1
  8. 打印 「 - 」
  9. x是1,以便打印出 「d」
  10. x現在是0
  11. 終止迴路

這給出了以下預期結果:a-b c-d

1

這將根據您的期望打印。

public class Shuffle1 { 
    public static void main(String[] args) { 
     int x = 3;  

     if(x > 2) { //First time x=3, which is true 
      System.out.print("a"); // print a 
     } 

     while(x > 0) { // x=3, which is true 
      x = x - 1; //first loop, x=2, then second loop x=1 
      System.out.print("-"); //prints "-" 

      if(x == 2) { // x=2, which is true 
      System.out.print("b c"); //prints "b c" 
      } 

     if(x == 1) { // as x=2, so it won't get display in first loop, but when it loop for second time, x become 1, which is true. 
      System.out.print("d"); 
      x = x - 1; 
      } 
     } 
    } 
} 
+0

請稍等片刻,我正在... – Ravi