簡體   English   中英

如何使用 if 語句檢查數組是否不包含值

[英]how to check if an array doesn't contain a value using an if statement

在我的代碼中,我創建了一個數組:

static BankClient clients[] = new BankClient[MAXCLIENTS]; // This array holds the clients up to a max of 1000

我需要做的是檢查這個數組,看看它是否包含一個特定的 int。 我能夠通過使用 for 循環和 if 語句成功地做到這一點,如下所示:

System.out.println("\n Ask for ID");
    System.out.println(">");
    IDInput = input.nextInt();              
    System.out.println("Check ID \n");

    for (int i = 0; i < clients.length; i++) 
    { 
        BankClient managementOptions = clients[i];
        
        if (managementOptions.getID() == IDInput) 
        {   
            // code in here                                 
        } 

但是,一旦我嘗試在底部放置一條 else 語句以向用戶寫入錯誤消息,由於 id 無效,它會繼續打印出保存在數組中與 id 不匹配的所有 id 的錯誤用戶給的。 這就是我想要的:

else if (// check if IDInput doesnt exist within the client array)
        {
            System.out.println("Error. Client does not exist.");
        }

但是我似乎不知道在括號之間放什么。 任何幫助將不勝感激。 這個網站還是很新的,所以如果您需要更多信息,我會盡力添加它。

如果您發現了什么,只需在循環中跟蹤:

boolean found=false;
for (int i = 0; i < clients.length; i++) 
    { 
        BankClient managementOptions = clients[i];
        
        if (managementOptions.getID() == IDInput) 
        {   
            found=true;                       
            break; // no need to search further
        } 
}
// no element found
if (!found){
 System.out.println("Error. Client does not exist.");
}

你不能只在循環中打印錯誤,因為你需要確保你已經查看了整個數組。

System.out.println("\n Ask for ID");
System.out.println(">");
IDInput = input.nextInt();              
System.out.println("Check ID \n");

boolean isPresent = false;
for (int i = 0; i < clients.length; i++) { 
  BankClient managementOptions = clients[i];
     
  if (managementOptions.getID() == IDInput) {   
      
      isPresent = true 
      
      // code in here                                 
  }
}

if (! isPresent) {
  System.out.println("Error. Client does not exist.");
} 

通過 Stream API 的簡單解決方案:

Boolean isPresent = Arrays.stream(clients).anyMatch(x -> x.getID().equals(IDInput));

暫無
暫無

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

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