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!
CodePudding user response:
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;
}
}