簡體   English   中英

檢查對象的列表數組中是否存在值

[英]Check if a value exists in an object's list array

你好,我在客戶端輸入 y 時循環

然后我想獲取您輸入的值並確保它包含在我的客戶列表中,但我不知道該怎么做

Scanner scanner = new Scanner( System.in );
ArrayList<Cliente> clientes = new ArrayList<Cliente>();
ArrayList<OrderService> orderService = new ArrayList<OrderService>();
System.out.println("add Cliente name")
string name = scanner.nextLine();
cliente.setName(name);
fazer um loop para se quiser adicionar mais clientes.

System.out.println("starting");

boolean value = true;
while(value)){
    System.out.println("Enter a new Client name");
    string name = scanner.nextLine();
    if(!name && name.trim().equals("")){
        Cliente cliente = new Cliente(name);
        clientes.add(cliente);
        System.out.println("Cliente "+cliente.getName+" Adicionado")
    }
    else{
        System.out.println("Nome invalido")
    }
    System.out.println("Do you want to add more client? Y for Yes, N for no");
    string response = scanner.nextLine(); 
    if(!response.equalsIgnoreCase(y)){
        value = false
    }
}

System.out.println("Enter a Client name that you want to create a work order.");
string clientName = scanner.nextLine();

嘗試使用流。

public static Cliente findByName(Collection<Cliente> clientes, String name)
{
    return clientes.stream().filter(cliente -> name.equals(cliente.getName())).findFirst().orElse(null);
}

您可以使用流 api 輕松實現您的問題假設您的Cliente類具有name屬性。 根據您提供的評論,您可以在第二個 if 語句中使用 checkedCliente

if(!name && name.trim().equals("")){
    Cliente checkedCliente = clientes.stream()
                .filter(x -> name.equals(x.getName()))    // check name is there?
                .findAny()
                .orElse(null);

    if(checkedCliente == null){
        Cliente cliente = new Cliente(name);
        clientes.add(cliente);
        System.out.println("Cliente "+cliente.getName+" Adicionado")
    }
    else {
        System.out.println("Cliente " + cliente.getName() + "is already in the collection");

        // checkedCliente can be used for updates etc in here.
    }
}

這是檢查數組列表是否包含字符串的方法

if(clientes.contains(name))

暫無
暫無

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

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