2016-03-02 83 views
1

Awnsers below工作,謝謝你們!Java:如果語句不起作用?

boolean Again = true; 
while (Again = true) 
{ 
    String input = JOptionPane.showInputDialog(null, "Input Za Number"); 
    try 
    { 
     int input2 = Integer.parseInt(input); 
     int R1 = 1; 
     int R2 = 1; 
     while (R2 < input2) 
     { 
      R1 = R1 * 2; 
      R2 = R2 + 1; 
      JOptionPane.showMessageDialog(null, R1); 
     } 
     String Ag = JOptionPane.showInputDialog(null, "Do it again? (Y/N)"); 
     if (Ag.equals("N")) 
     { 
      Again = false; 
     } 
    } 
    catch(Exception e) 
    { 
     JOptionPane.showMessageDialog(null, "What is '" + input + "'?!?! Enter an actual number."); 
    } 
} 

我把部分那不是工作,我希望能在大膽。它的「if(Ag.equals(」N「))」。我試圖做到這一點,如果用戶輸入「N」,那麼程序將停止運行。否則它會循環並繼續前進。問題是,即使我輸入N,它也會循環。我沒有得到任何錯誤。請幫幫忙,我感到非常迷惑:(

+3

'而(再次= TRUE)'必須',而(同樣==真)'(或簡單地'while(Again)') –

+0

感謝安德烈亞斯,你的解決方案解決了它:D – KiwiNinja

+0

最後,你是壞習慣的受害者。只需避免'someBool == true'(或false)。只要做'if(someBool)'或while,或者...除此之外:閱讀關於命名約定 - 變量名稱以小寫字母開頭。並且:給你正在使用的東西**有意義的**名稱:「input2」意味着什麼。 R1意味着什麼。 R2意味着什麼。 – GhostCat

回答

4

這是一個典型的例子,爲什麼專業開發商總是會使用

if (null == object) 

if (object == null) 

在錄入錯誤的情況下,如下面的

// as posted 
while (Again = true) // works, always true 

// the other way 
while (true = Again) // compiler error 

的方式因爲發佈將重新分配值true再次每次重複循環;如果語句是用另一種方式寫的,編譯器會拋出一個錯誤,指出你不能將值賦給true

只需單等號,你重新分配的每次再次真正你這裏的值,其中作爲雙等於檢查是否相等。

在像這樣的情況下,你真的甚至不需要true,你可以簡單地使用

while (Again) 
// or again 
while (true == Again) 

relevant

2

當你做這樣的事情

while (Again = true) 

你實際上將變量賦值爲true

是讓你無限時...


做,而不是

while (Again) // since is boolean you dont need to compare against a true value..