我正在尝试制作一种小方法,允许用户将犯罪行为输入“犯罪数据库”,并且仅显示实施该犯罪的罪犯。
不幸的是,我必须使用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.");
}