2013-10-05 33 views
0

這是一本來自教科書的練習課程。我需要弄清楚這個程序的出版物。 這裏的程序:如何計算此程序中的最終輸出印數?

public class EchoTestDrive { 
    public static void main(String[] args) { 
     Echo e1 = new Echo(); 
     Echo e2 = new Echo(); 

     int x = 0; 
     while (x < 4) { 
      e1.hello(); 
      e1.count = e1.count + 1; 
      if (x == 3) { 
       e2.count = e2.count + 1; 
      } 
      if (x > 0) { 
       e2.count = e2.count + e1.count; 
      } 
      x = x + 1; 
     } 
     System.out.println(e2.count); 
    } 
} 

class Echo { 
    int count = 0; 

    void hello() { 
     System.out.println("helloooo... "); 
    } 
} 

對這一計劃的絕版的答案是:

helloooo... 
helloooo... 
helloooo... 
helloooo... 
10 

我不太明白這是如何計算爲主。它似乎像x循環4次。 X = 0; X = 1; X = 2; X = 3。並且e1應該具有值1,2,3,4,因爲e1.count = e1.count + 1。 然後我很困惑,在這種情況下如何計算e2?

+1

請正確縮進您的代碼。 – arshajii

+0

你到底想做什麼?你能發佈你的預期結果嗎? – Andromeda

+1

最好的方法是在IDE中調試代碼。如果不寫入控制檯,while循環內的值可以看到循環如何執行 –

回答

1

觀測變量輸出

public class EchoTestDrive { 
    public static void main(String[] args) { 
     Echo e1 = new Echo(); 
     Echo e2 = new Echo(); 

     int x = 0; 
     while (x < 4) { 
      e1.hello(); 
      e1.count = e1.count + 1; 
      System.out.println("e1.count = " + e1.count); 
      if (x == 3) { 
       e2.count = e2.count + 1; 
       System.out.println("x == 3 e2.count = " + e2.count); 
      } 
      if (x > 0) { 
       e2.count = e2.count + e1.count; 
       System.out.println("x > 0 e2.count = " + e2.count); 
      } 

      x = x + 1; 
     } 
     System.out.println(e2.count); 
    } 
} 
+0

我看到了!但爲什麼e2只輸出最後一個週期值,即10? –

+0

沒關係!我懂了! –

0

化妝的x,e1.count,和e2.count的表。然後只需按照程序一行一行地更新值。我得到10的e2.count的最終價值。對於x = 0,e2.count保持爲0。但它在x = 3時得到額外的增量。