2014-04-01 21 views
0

以下程序過早退出while循環。如果我拿出||只剩下一個選項離開循環,那麼它工作正常。但是,我但我不想要這個;我希望有多種條件擺脫循環,而不僅僅是一個。多部分環路條件不應該是

public class password 
{ 
    public static void main (String args[]) 
    { 
     new password(); 
    } 

    public password() 
    { 
     String guess = ""; 

     //while they haven't got the password yet 
     while (!guess.equals ("Rain") || !guess.equals ("rain")) 
     { 
      guess = IBIO.inputString ("Enter the password: "); 

      if (!guess.equals ("Rain") || !guess.equals ("rain")) 
      { 
       System.out.println ("Sorry please try again."); 
      } 

     } 
     //if they are out of the loop, they got the password 
     System.out.println ("Correct, please continue"); 
    } 
} 
+1

如果你打算使用無括號的'if'語句,至少應該把語句放在'if'語句附近,否則你會在'if'和'System.out.println之間意外地輸入另一個語句'因爲括號內沒有明確的說明。在Java中總是使用括號和if語句通常是一個好習慣。我有時不會,但我確定它非常清楚。將它傳播出去會讓它變得更加混亂/難看。 – Matthew

回答

2

更改||&&

if (!guess.equals ("Rain") || !guess.equals ("rain")) 

true如果guess不等於 「雨」,或者如果guess不等於 「雨」。如果guess等於「Rain」,那麼它不等於「rain」,因此if語句的計算結果爲true,當您希望它爲false時。

同樣適用於您的while的情況。

String guess = "rain"; 
System.out.println(!guess.equals("Rain")); // Outputs true 
System.out.println(!guess.equals("rain")); // Outputs false 

那麼,你是||荷蘭國際集團一truefalse,其結果將是true

0

您的情況是總是對的現在,因爲雙方同時不可能是虛假的。它看起來像你想要&&(和)而不是||(或),以便猜測是正確的,如果它等於"Rain""rain"

這裏的真正問題可能在於,您組織的代碼的方式使得思考比您真正需要的更困難。直觀地說,你想要做的是「循環直到用戶輸入"Rain""rain"」。因爲你的循環設置了所有的否定,所以很難閱讀,因此很難編碼。爲了便於理解這是怎麼回事,我會使用一個建築看起來更像直觀的設計:

while (true) { // loop "forever" 
    guess = IBIO.inputString ("Enter the password: "); 
    if (guess.equals("Rain") || guess.equals("rain")) { 
     break; // They got the password right; break out of the loop. 
    } 
    // If we get here, they got the password wrong, so tell them and keep looping. 
    System.out.println ("Sorry please try again."); 
} 
System.out.println ("Correct, please continue"); 
0

當然||必須&&這裏,

這是一個錯誤模式不comparison1或不comparison2

!guess.equals ("Rain") || !guess.equals ("rain") 

無論comparison1或comparison2是假的所以結果總是正確的 - 信息丟失。 因此,如果不考慮含義,它可能是&&