簡體   English   中英

有人可以解釋為什么while語句必須為AND

[英]Can someone Explain Why This While Statement Has to be AND

因此,基本上,我在理解不允許該語句使用“ OR”但不能使用“ 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!");
          }

      }
  }

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

您可以使用或進行操作:

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

以來

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

這就是德摩根定律

另外,最好只在一個地方放置條件:

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!");

這是因為您不希望對Y,Y,N,N也沒有響應。

做OR || 如果您是Y,您就不是y會導致邏輯崩潰,因此OR會返回true

|| 在任何時候都會使該陳述為真。

帶X

真,因為它不會是Y,y,N,N,所以True or TrueTrueTrue == True

如果您輸入任何條件(Y,y,n,N),它將給出True或true或true或false(以各種順序)== true

您可以做很多事情來改進此代碼。 考慮

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的答案解釋了為什么您的邏輯是錯誤的。

&&稱為邏輯AND運算符。 如果兩個操作數都不為零,則條件變為true。

|| 稱為邏輯或運算符。 如果兩個操作數中的任何一個都不為零,則條件變為true。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM