如何在 java 中使用线性搜索?

how to use linear search in java?

我有一组 [3][3] ID、姓名、城市,如果我必须接受用户输入(即姓名),然后显示人的其他详细信息,如 ID 和城市

public class Source {

    String customerDetails[][]=new String[5][3];

    Source() {
        customerDetails[0][0]="1001";
        customerDetails[0][1]="Nick";
        customerDetails[0][2]="Chicago";
    
        customerDetails[1][0]="1008";
        customerDetails[1][1]="James";
        customerDetails[1][0]="San Diego";
        
        customerDetails[2][0]="1002";
        customerDetails[2][1]="Tony";
        customerDetails[2][2]="New York";
        
        customerDetails[3][0]="1204";
        customerDetails[3][1]="Tom";
        customerDetails[3][2]="Houston";
        
        customerDetails[4][0]="1005";
        customerDetails[4][1]="Milly";
        customerDetails[4][2]="San Francisco";
    }

}

请指教。我是 java 的新手,谢谢!

您需要遍历二维数组并匹配给定的用户名,数组中的每个名称,如果找到匹配项,您可以 return 将用户详细信息包装在自定义 class

public List<Customer> findCustomersByName(String customerName) {
    int length = customerDetails.length;
    List<Customer> customersmatching = new ArrayList<>();

    for (int i = 0; i < length; i++) {
        if (customerName != null && customerName.equals(customerDetails[i][1])) {
            customersmatching.add(new Customer(customerDetails[i][0], customerDetails[i][1], customerDetails[i][2]));
        }
    }
    return customersmatching;
}

private static class Customer {
    String userId;
    String userName;
    String userCity;

    public Customer(String userId, String userName, String userCity) {
        this.userId = userId;
        this.userName = userName;
        this.userCity = userCity;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserCity() {
        return userCity;
    }

    public void setUserCity(String userCity) {
        this.userCity = userCity;
    }

}