0

我正在尝试制作一个小方法,允许用户将犯罪输入到“犯罪数据库”中,它只会显示犯下该罪行的罪犯。

不幸的是,我必须使用二维数组。我写了一个方法,但它没有给我我正在寻找的输出。

这是方法:

    //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

你能帮我弄清楚这有什么问题吗?提前致谢。:)

4

2 回答 2

1

您一直在打印最后发现的罪犯(旗帜)。

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.");
}
于 2013-09-20T10:55:22.957 回答
1

只是一些小的添加来增强代码重用和可维护性(如果需要):

  • 您已经明白,在许多现实生活中,使用数组并不是最好的(= 最“可读”)解决方案,因为符号(自然语言)通常比普通数字更容易理解 - 编辑:在这种情况下使用常量可能已经比字面数字更好
  • for尽可能使用增强型循环而不是显式元素寻址: Java 中增强型 for 循环的语法是什么?
  • 而不是与您进行比较,false您可能希望使用!运算符来使您的代码更具可读性
  • .equals.compareTo .. == 0(至少在这种情况下)更清晰
于 2013-09-20T11:18:52.890 回答