[英]Searching keyword in a 2D array
我試圖制作一個小方法,允許用戶將犯罪輸入“犯罪數據庫”,它只會顯示犯下該罪行的罪犯。
不幸的是,我必須使用2D數組。 我寫了一個方法,但它沒有給我我正在尋找的輸出。
這是方法:
//method to search data
public static void searchData() throws IOException{
int flag = 0;
boolean found = false;
//input search key
System.out.print("Which crime would you like to select? (arson, theft, assault) ");
String searchKey = br.readLine();
System.out.println("You searched for criminals with the offence of \"" + searchKey + "\".");
System.out.println("Name - Crime - Year of Conviction");
for(int i = 0; i < criminals.length; i++){
if(searchKey.compareTo(criminals[i][1]) == 0){
flag = i;
found = true;
}
}
if(found == false){
System.out.println("Error! Crime not found.");
}else{
System.out.println("Criminals found.");
for(int i = 0; i < criminals.length; i++){
System.out.println(criminals[flag][0] + " - " + criminals[flag][1] + " - " + criminals[flag][2]);
}
}
}
我的意見如下:
George - theft - 1999
Eddie - assault - 2003
Al - theft - 1999
這是測試后的輸出:
Which crime would you like to select? (arson, theft, assault) theft
You searched for criminals with the offence of "theft".
Criminals found.
Al - theft - 1999
Al - theft - 1999
Al - theft - 1999
你能幫我弄清楚這有什么問題嗎? 提前致謝。 :)
你一直在打印最后發現的罪犯(國旗)。
for(int i = 0; i < criminals.length; i++){
if(searchKey.compareTo(criminals[i][1]) == 0){
if(!found) {
found = true;
System.out.println("Criminals found.");
}
System.out.println(criminals[i][0] + " - " + criminals[i][1] + " - " + criminals[i][2]);
}
}
if(found == false){
System.out.println("Error! Crime not found.");
}
只是一些小的補充,以增強代碼重用和可維護性(如果需要):
for
循環而不是顯式元素尋址: Java中增強for循環的語法是什么? false
你可能想要使用!
運算符使您的代碼更具可讀性 .equals
比.compareTo .. == 0
更清晰(至少在這種情況下)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.