搜索数组的麻烦

时间:2018-05-27 05:56:46

标签: java arrays search

我的程序假设允许用户输入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 :(得分:3)

您只保留找到的最后一个匹配项的索引。你应该在循环中打印匹配项:

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

答案 1 :(得分:0)

你需要一个数组,如下所示:

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

答案 2 :(得分:0)

问题出现在你的循环中

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

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

                    flag = x;
                    found = true;
                }
            }

你正在做的是你循环记录并将索引值存储到flag,它总是被覆盖,你将拥有最后一个值。要解决此问题,要么在循环中打印值,要么使用空数组,并在查找结果时在数组中添加值。

答案 3 :(得分:0)

查看你的代码,只需将其中的代码移动到else部分(如果匹配的记录在那里它打印标题和记录)到compareTo条件下的for循环,并删除那个else条件if(found == false)。我希望将解决此问题

答案 4 :(得分:0)

我认为你选择了非法的数据结构。如果您想根据某个特定密钥(例如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;
    }
}
相关问题