簡體   English   中英

為什么這個while循環不終止? 比較整數

[英]Why is this while loop not terminating? Comparing ints

我正在嘗試創建一種菜單。 並且,如果菜單中的任何選項均未選中,則應繼續重復這些選項。 但是,這個while循環不是終點,我不確定為什么。

我懷疑這與我比較我的積分有關。

Scanner s = new Scanner(System.in);
int inp = s.nextInt();

while (inp != 1 || inp != 2 || inp != 3 || inp != 4) {
    System.out.println("Not one of the options");
    System.out.println("Please choose an option:");
    System.out.println("\t1) Edit Property");
    System.out.println("\t2) View More info on Property");
    System.out.println("\t3) Remove Property");
    System.out.println("\t4) Return");

    s = new Scanner(System.in);
    inp = s.nextInt();
}
inp != 1 || inp != 2

該條件始終為真:

  • 如果inp為42,則第一個操作數為true,第二個操作數也為true,因此結果為true
  • 如果inp為1,則第一個操作數為false,第二個為true,因此結果為true
  • 如果inp為2,則第一個操作數為true,第二個為false,因此結果為true

您要&&而不是||

或者你也可以使用

while (!(inp == 1 || inp == 2 || inp == 3 || inp == 4))

或更簡單:

while (inp < 1 || inp > 4)

嘗試替換|| &&像這樣:

  while(inp != 1 && inp != 2 && inp != 3 && inp != 4 ){

因為第一個條件是|| 永遠是真的。

您需要使用&&進行檢查。 無論輸入什么,至少4個中的3個或語句為true,因此循環將再次循環

除了使用&&的其他答案之外,您還可以拉出否定的答案,因為您想檢查“同時不選擇任何選項”,即“ (此那個其他東西)”

while (!(inp == 1 || inp == 2 || inp == 3 || inp == 4))) {

}

您的情況表述錯誤,

這個:

while (inp != 1 || inp != 2 || inp != 3 || inp != 4) {

必須替換為

while (inp != 1 && inp != 2 && inp != 3 && inp != 4) {

暫無
暫無

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

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