2014-07-13 37 views
2

所以基本上我有一些麻煩理解不允許此語句使用「或」的邏輯,但完美地使用「AND」。按我的邏輯說,等於Y或Y或N或N,應該工作。但是如果我使用這個它是一個無限循環。代碼塊可以在下面看到;有人可以解釋爲什麼這雖然聲明必須和

 response = "empty"; 
     while (!response.equals("Y") && !response.equals("y") && !response.equals("N") && !response.equals("n")) 
     { 
      response = stdin.next(); 
      if (!response.equals("Y") && !response.equals("y") && !response.equals("N") && !response.equals("n")) { 
       System.out.println("Try again, you're still in the loop!"); 
      } 
      else { 
       System.out.println("Congratulations you're out the loop!"); 
      } 

     } 
    } 

任何人都可以向我解釋的邏輯原因||不能使用,但& &完美的作品。其餘的代碼(掃描儀等都在上面,但我沒有包括它們,因爲它們不相關)。 謝謝!

+4

您可能需要使用'equalsIgnoreCase()'。 –

+0

讓我介紹一下['String.equalsIgnoreCase(String s)'](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase%28java.lang.String% 29)。它會爲你整理一些東西。 – indivisible

+0

你的if語句沒有意義。無論你在循環中。 – Brian

回答

4

你可以用或做:

while (!(response.equalsIgnoreCase("Y") || response.equalsIgnoreCase("N"))) 

由於

(!A && !B && !C) is equivalent to !(A || B || C) 

這就是所謂的De Morgan's Law

此外,這將是最好具備的條件只在一個地方:

response = stdin.next(); 
while (!(response.equalsIgnoreCase("Y") || response.equalsIgnoreCase("N"))) 
{ 
    System.out.println("Try again, you're still in the loop!"); 
    response = stdin.next(); 
} 
System.out.println("Congratulations you're out of the loop!"); 
+0

「德摩根定律」供參考。 – Rogue

+0

@盜賊感謝您的評論。增加了參考 – Eran

+0

它修復了數學部分,但沒有解釋爲什麼他的情況不起作用,這主要是問題 – Fawar

0

這是因爲你想要的響應不是Y,或y也不ñ也不ñ。

做什麼或||會崩潰的邏輯有,如果你有Y,你是不是y和因此或將返回true

||會使語句在所有的時間是正確的。

隨着X

真實的,因爲它不會是Y,或y,也不是N,也不ñ 所以True or TrueTrueTrue == True

如果你把所有的條件(Y,Y,N ,N)它會給 真或假或真或假(按各種順序)== true

0

有很多你可以做的改進這個代碼。考慮

response = stdin.next(); 
while (!response.equalsIgnoreCase("y") || !response.equalsIgnoreCase("n")) 
{ 
    System.out.println("Try again, you're still in the loop!"); 
    response = stdin.next();     
} 
System.out.println("Congratulations you're out the loop!"); 

@Eran的答案解釋了爲什麼你的邏輯錯誤。

0

&&稱爲邏輯AND運算符。如果兩個操作數都不爲零,則條件成立。

||稱爲邏輯OR運算符。如果兩個操作數中的任何一個非零,則條件成立。

enter image description here

相關問題