簡體   English   中英

在2D數組中搜索關鍵字

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM