Проблема с поиском в массиве - PullRequest
0 голосов
/ 27 мая 2018

Предполагается, что моя программа позволяет пользователю вводить данные о судимости 8 преступников;их имя, преступление и дата осуждения.После ввода он запросит у пользователя конкретный тип преступления, которое он ищет, и напечатает полную статистику по всем преступникам, которые были признаны виновными в преступлении в той категории, которую запрашивал сотрудник (есть только три преступления: кража, поджог иНападение).

Моя проблема заключается в том, что программа показывает только 1 криминальную историю, если я прошу найти одно из преступлений, когда есть несколько других записей с таким же преступлением.

Вот мой код:

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

                }


            }

}

Это пример ввода:

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

Это образецвывод:

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

Ответы [ 5 ]

0 голосов
/ 27 мая 2018

Я думаю, что вы выбрали незаконную структуру данных.Если вы хотите собрать базу данных по какому-то конкретному ключу (crime в вашем примере), тогда вам следует подумать об использовании Map.

Еще одна вещь.Зачем вам несколько экземпляров Scanner?Более того, в то же время вы используете BufferedReader вместо того же 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;
    }
}
0 голосов
/ 27 мая 2018

Глядя на ваш код, просто переместите код в разделе else (где он печатает заголовок и записи, если есть совпадающие записи) в цикл for в условии CompareTo и удалите условие else в if (found == false). Я надеюсь, чтоэто исправит

0 голосов
/ 27 мая 2018

Вам нужен массив, например:

//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);
}
0 голосов
/ 27 мая 2018

проблема здесь в вашем цикле

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

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

                    flag = x;
                    found = true;
                }
            }

то, что вы делаете, это то, что вы просматриваете свою запись и сохраняете значения индекса в flag, который всегда переопределяется, и у вас будет последнее значение.Для решения этой проблемы либо вы печатаете свои значения в цикле, либо имеете пустой массив и добавляете значение в массив при нахождении результата.

0 голосов
/ 27 мая 2018

Вы сохраняете индекс только последнего найденного совпадения.Вы должны напечатать спички внутри цикла:

            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");
            }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...