java - 在二维数组中搜索关键字

标签 java search

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

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

方法如下:

    //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.");
}

关于java - 在二维数组中搜索关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18914965/

相关文章:

java - ArrayList.indexOf 与对象数组的顺序搜索

java - 扩展 Eclipse Java 搜索

java - spring.profiles.active 在 spring boot 应用程序中不起作用

java - 如何从 Access JDBC ODBC 数据库的表中获取 java 中的行数

java - xmlhttprequest 获取加密 key + html 表单 - 我做错了什么

java - 带 OpenGL 的基本 LWJGL 三角形

Java 正则表达式从字符串中删除 SQL 注释

java - 使用用户输入搜索对象数组,验证输入

javascript - 修改后无法搜索多选

database - elasticsearch如何使用精确搜索并忽略关键字中的关键字特殊字符?