Mina
Mina

Reputation: 45

Trouble with Searching Array

My program is suppose to allow the user to input the criminal records of 8 criminals; their name, offence, and conviction date. After input, it will ask the user for a specific type of crime they are searching for and print complete statistics on all criminals who were found guilty of the crime in the category that the officer requested (There are only three crimes: Theft, Arson and Assault).

My problem is that the program is only showing 1 criminal record if I ask to find one of the crimes, when their are several other records with the same crime.

Here is my code:

//Include Libraries
import java.io.*;
import java.util.Scanner;

//Class
public class Police {

//Declare variables, Arrays, and Strings for future use in the program
static String name[] = new String[8]; //Name Array that can hold 8 names
static String crime[] = new String[8]; //Position Array that can hold 8 crimes
static int year[] = new int[8]; //Age Array that can hold 8 years
    static int x, i; //x and i are counters

    //Main Method
    public static void main(String[] args) throws IOException {

        //Open BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

         /* 
         * The program will now loop the menu
         * options shown below.
         * It will loop until the user exits 
         * the program.
         */

        //variable for menu 
        int menuChoice = 1;
        //Display introduction
        System.out.print("Hello and Welcome to Police Java Database\r");

        while (menuChoice != 3) {
            //Display menu choices
            System.out.print("Enter Menu Choice\n");
            System.out.print("**********************");
            System.out.print("\r(1) => Enter Criminal Data \n");
            System.out.print("(2) => Display Matching Crime \n");
            System.out.print("(3) => Exit Program \r");

            //try-catch statement to read input 
            try {

            menuChoice = Integer.parseInt(br.readLine());
            } catch (IOException ie) {
                ie.printStackTrace();
            }
            //switch statement to loop the menu choices
            switch(menuChoice) {
            case 1:
                //Case 1 is the store input method
                inputInfo();
                break;
            case 2:
                //Case 2 is the sort input method
                inputSearch();
                break;
            case 3:
                //exit program for case 3
                return;
            }

        }

        /* 
         * The program will now begin to store
         * each input information from the user
         * about each criminal in Arrays.
         */

    }
        //Method to store input info    
         public static void inputInfo() throws IOException { 

         //Open BufferedReader
         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

         //Open Scanner
         Scanner p = new Scanner(System.in); 

         //loop to request to fill Arrays   
            for (x = 0; x < 8; x++) {

                //Ask for criminal name input
                System.out.print("Enter criminal name: ");
                //Read input and store name in an Array
                name[x] = in.readLine();

                //Ask for crime input 
                System.out.print("Enter crime offence: ");
                //Read input and store crime in an Array
                crime[x] = in.readLine();

                //Ask for year the crime was committed
                System.out.print("Enter year of conviction: \r"); 
                //Read input and store year in an Array
                year[x] = p.nextInt();


            }

            /* 
             * The program will now begin to search 
             * the stored information for matching crime.
             */

         }


            //Method to select and find info
            public static void inputSearch() throws IOException {

                //Open BufferedReader
             BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
                //declare variables that'll be used to search crime input
                int flag;
                boolean found;
                String searchcrime;
                flag = 0;
                found = false;

                //Ask what crime the user is searching for
                System.out.print("What is the crime you're searching for: ");
                //Read the input
                searchcrime =sc.readLine();
                //Display which crime they selected
                System.out.print("You searched for criminals with the offence of: " + searchcrime + "\r");

                //Compare all input for asked crime 
                for (x = 0; x < 8; x++) {

                    if (searchcrime.compareTo(crime[x])==0) {

                        flag = x;
                        found = true;
                    }
                }


                //If the input is not found, show error
                if (found == false) {

                    System.out.print("Error! Crime not found");
                }
                else {

                    //Display each category of records; names, crime, year
                     System.out.println(" Name " + " -----" + " Crime " + "-----" + " Year ");
                    //Display matching crime with criminal name and year of conviction.
                    System.out.println( name[flag] + " --- " + crime[flag] + " --- " + year[flag]);

                }


            }

}

This is a sample of the input:

Bugs Malone, Theft, 1981
Slippery Sal, Theft, 1991
Al Copone, Assault, 1947
Eddie Striker, Arson, 1969
Tom Tuner, Arson, 2005
Gared Gipson,Assault, 1998
Jary Lucky, Arson, 2013
Lizzy Patty, Theft, 2009

This is a sample of the output:

What is the crime you're searching for: Arson
You searched for criminals with the offence of:Arson
 Name  ----- Crime ----- Year 
Jary Lucky --- Arson --- 2013

Upvotes: 1

Views: 124

Answers (5)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

I think you have choosen illegal data structure. In case you want to collect data base on some specific key (crime in you example), then you should think about using Map.

One more thing. Why do you you several instance of Scanner? Moreover, at the same time you use BufferedReader instead of using same Scanner isntance.

public class Police {

    public static void main(String[] args) {
        try (Scanner scan = new Scanner(System.in)) {
            Map<String, List<CriminalRecord>> map = new HashMap<>();

            System.out.print("Hello and Welcome to Police Java Database\r");

            while (true) {
                System.out.println("Enter Menu Choice");
                System.out.println("**********************");
                System.out.println("(1) => Enter Criminal Data");
                System.out.println("(2) => Display Matching Crime");
                System.out.println("(3) => Exit Program");

                int menu = scan.nextInt();
                scan.nextLine();

                if (menu == 1)
                    inputInfo(scan, map);
                else if (menu == 2)
                    inputSearch(scan, map);
                else
                    return;
            }
        }
    }

    private static void inputInfo(Scanner scan, Map<String, List<CriminalRecord>> map) {
        final int total = 8;

        for (int i = 0; i < total; i++) {
            CriminalRecord record = new CriminalRecord();

            System.out.printf("%d/%d: Enter criminal name: ", i + 1, total);
            record.name = scan.nextLine();

            System.out.printf("%d/%d: Enter crime offence: ", i + 1, total);
            record.crime = scan.nextLine();

            System.out.printf("%d/%d: Enter year of conviction: ", i + 1, total);
            record.year = scan.nextInt();
            scan.nextLine();

            String key = record.crime.toLowerCase();

            if (!map.containsKey(key))
                map.put(key, new ArrayList<>());

            map.get(key).add(record);

            System.out.println();
        }
    }

    private static void inputSearch(Scanner scan, Map<String, List<CriminalRecord>> map) {
        System.out.print("What is the crime you're searching for: ");
        String crime = scan.nextLine();
        System.out.println("You searched for criminals with the offence of: " + crime);

        List<CriminalRecord> records = map.get(crime.toLowerCase());

        if (records == null || records.isEmpty())
            System.err.println("Error! Crime not found");
        else {
            System.out.println(" Name " + " -----" + " Crime " + "-----" + " Year ");
            records.forEach(record -> System.out.println(record.name + " --- " + record.crime + " --- " + record.year));
        }
    }

    private static final class CriminalRecord {

        private String crime;
        private String name;
        private int year;
    }
}

Upvotes: 0

Tarun Sawlani
Tarun Sawlani

Reputation: 34

Looking to your code, just move code in else section (where it prints header and records if matching records are there ) to for loop under compareTo condition and remove that else condition over if (found ==false).I hope that will fix this

Upvotes: 0

hiren
hiren

Reputation: 1812

the problem is here in your loop

           for (x = 0; x < 8; x++) {

                if (searchcrime.compareTo(crime[x])==0) {

                    flag = x;
                    found = true;
                }
            }

what you are doing is you are looping through your record and storing values of index to flag which always gets override and you will have last value. To solve this either you print your values in the loop or have empty array and add the value in array on finding the result.

Upvotes: 0

Guilherme Mussi
Guilherme Mussi

Reputation: 1057

You need an array, like this:

//Compare all input for asked crime 
List<String> crimesFound = new ArrayList();
for (x = 0; x < 8; x++) {
  if (searchcrime.equalsIgnoreCase(crime[x])) {
    flag = x;
    crimesFound.add(crime);
  }
}


//If the input is not found, show error
if (crimesFound.isEmpty()) {
  System.out.print("Error! Crime not found");
} else {
   // print all crimes found
  System.out.println("Crimes found " + crimesFound);
}

Upvotes: 0

Eran
Eran

Reputation: 393781

You are only keeping the index of the last match found. You should print the matches inside the loop:

            for (x = 0; x < 8; x++) {
                if (searchcrime.compareTo(crime[x])==0) {
                    if (!found) { // print title before first match
                        System.out.println(" Name " + " -----" + " Crime " + "-----" + " Year ");
                    }          
                    System.out.println( name[x] + " --- " + crime[x] + " --- " + year[x]);
                    found = true;
                }
            }
            if (!found) {
                System.out.print("Error! Crime not found");
            }

Upvotes: 3

Related Questions