[英]Check first element on a 2D array in JAVA
假設我們有一個如下的二維數組,
[[name1, g, t, w, q, p], [name2, b, g, f, y, o]]
我正在創建一個地址簿,它采用這個二維數組並根據 name1、name2 等搜索內部 arrays。為此,我創建了以下代碼,
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");
}
}
問題是當我在終端上輸入 name1 或 2 時,我收到 else 語句。 我究竟做錯了什么?
您收到 else 是因為一旦發現發生了retrieve
,您就不會停下來繼續尋找另一個列表。
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");
}
}
lambda 似乎也可讀,
catalog.stream().filter(l -> l.get(0).contains(retrieve)).findFirst().ifPresentOrElse(l -> {
l.indexOf(retrieve);
System.out.println("FOUND");
}, () -> System.out.println("Not found"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.