Suppose we have a 2d array as follows,
[[name1, g, t, w, q, p], [name2, b, g, f, y, o]]
I am creating an address book that takes this 2d array and searches the inner arrays based on name1, name2 etc. For that purpose I created the following code,
if (catalog.isEmpty()){
System.out.println("Address book is empty!!!\n");
continue;
}
System.out.println("Choose the contact name for search");
Scanner retrieve_input = new Scanner(System.in);
String retrieve = retrieve_input.nextLine();
for (ArrayList<String> list : catalog) {
if (list.get(0).contains(retrieve)) {
list.indexOf(retrieve);
System.out.println(catalog);
} else {
System.out.println("There's no such name in the book\n");
}
}
The problem is when I am typing the name1 or 2 on the terminal, I am receiving the else statement. What am I doing wrong?
You are receiving the else because once you find the occurence of retrieve
, you don't stop and continue looking to the other list.
for (ArrayList<String> list : catalog) {
if (list.get(0).contains(retrieve)) {
list.indexOf(retrieve);
System.out.println("FOUND");
break; // <-------- break if found
} else {
System.out.println("There's no such name in the book\n");
}
}
A lambda seems readable as well,
catalog.stream().filter(l -> l.get(0).contains(retrieve)).findFirst().ifPresentOrElse(l -> {
l.indexOf(retrieve);
System.out.println("FOUND");
}, () -> System.out.println("Not found"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.