2013-10-26 32 views
-2

我想運行一個while循環程序,與輸入無關。它只是想告訴我計算的最終價值是什麼。但是,當我運行該程序時,它什麼都不做。它也沒有結束。我對發生的事情感到困惑?雖然循環無緣無故地尋找意外的輸入?

int x = 90; 
    while (x < 100) 
    { 
     x += 5; 
     if (x > 95) 
      x -= 25; 
    } 
    System.out.println("final value for x is " + x); 
+1

它總是在循環,所以它永遠不會到達println :)如果你想知道它是否工作,把println放在循環中。 – Alex

+1

你期望結果是什麼? –

回答

0

發生什麼事是你while循環從不停歇,所以它永遠不會打印出一些東西,嘗試改變循環內的代碼。

你怎麼能意識到這一點?

把一些打印出和while循環中:

int x = 90; 
    System.out.println("Before the while"); 
    while (x < 100) { 
     System.out.println("Inside the while"); 
     x += 5; 
     if (x > 95) 
      x -= 25; 
    } 
    System.out.println("final value for x is " + x); 

迭代1:

x = 95 

迭代2:

x = 100 
if condition is true, so x = 75 

...所以每當x達到100條件將使它成爲75.因此,時間永遠不會結束。

+0

我認爲這是我的教授的意圖。他只是想讓我們弄清楚結果是什麼。我只是想確保我的執行沒有任何問題。 – WeekzGod

0

循環永遠不會終止,因爲x從未達到100。如果你想看到自己發生了什麼x,一行添加到您的循環,這樣的代碼如下所示:

int x = 90; 
while (x < 100) { 
    System.out.println("x = " + x); // More useful output here... 
    x += 5; 
    if (x > 95) 
     x -= 25; 
} 
System.out.println("final value for x is " + x);