0

I'm trying to make a small method that will allow a user to input a crime into a "criminal database" and it will show only the criminals that committed that crime.

Unfortunately, I have to use a 2D array. I've written a method, but it's not giving me the output I'm looking for.

Here's the method:

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

My input was this:

George - theft - 1999
Eddie - assault - 2003
Al - theft - 1999

And here is the output after testing:

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

Could you help me figure out what's wrong with this? Thanks in advance. :)

Sal
  • 109
  • 1
  • 2
  • 8

2 Answers2

1

You have been printing last found criminal (flag).

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.");
}
tomwesolowski
  • 956
  • 1
  • 11
  • 27
1

Just some small additions to enhance code reuse and maintainability (if desired):

  • you've already understood that using arrays is not the best (= most "readable") solution in many real-life cases, since a symbol (natural language) is usually better understood than a plain number - EDIT: in this case using constants may already be better than literal numbers
  • use the enhanced for loop instead of explicit element addressing whenever possible: What is the syntax of enhanced for loop in Java?
  • instead of comparing to false you may want to use the ! operator to make your code more readable
  • also, .equals is clearer than .compareTo .. == 0 (at least in this case)
Community
  • 1
  • 1