2

I have one array of [3][3] ID, Name, City if I've to take user input (ie Name) and then display the other details of person like id and city

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";
    }

}

Please advise me. I'm new to java, Thanks!

3
  • 4
    Use a for loop? Commented Mar 22, 2022 at 5:24
  • It helps when you draw out the 2D arrays as rows and columns. Commented Mar 22, 2022 at 5:29
  • Rather than using a 2D array, create a CustomerDetails class and use an ArrayList<CustomerDetails> Commented Mar 22, 2022 at 5:39

1 Answer 1

1

You need to iterate through the 2D array and need to match the given userName, with each Name in the array and if match is found you can return the user details wrapped in a custom 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;
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.