【问题标题】:Take user input and search through 2D array and printout the result获取用户输入并搜索二维数组并打印结果
【发布时间】:2021-11-03 18:37:52
【问题描述】:

我正在尝试制作一个程序,该程序从用户那里获取输入,搜索二维数组并打印出输入是否与数组中的数据匹配。所以,基本上如果用户输入VA,它应该输出Virginia。我正在从具有 2 行数据的二进制文件中读取数据。第一行包含所有州的 2 个字母缩写,第二行包含州名。例如:VA Virginia 和新行 FL Florida 等等。以下是我到目前为止所拥有的。 readStateFile() 方法工作正常。我只需要getState 方法的帮助。

public static void main(String[] args) throws IOException {
        try {
            int age = getAge();
            String[][] states = readStateFile();
            String state = getState(states);

            int ZIPCode = getZIPcode();

            System.out.printf("\nAge:\t\t%d\n", age);
            System.out.printf("Address:\t%s %s\n\n", ZIPCode, state);

            System.out.println("Your survey is complete. " + "Your participation has been valuable.");
        } catch (CancelledSurveyException e) {
            System.out.println(e.getMessage());
        } finally {
            System.out.println("Thank you for your time.");
        }
    }
private static String getState(String[][] states) throws IOException {

        states = readStateFile();

        String in = "";
        String[][] abb;
        abb = states;

        System.out.println("Please enter the 2 letter state abbrevation or 'q' to quit: ");
        Scanner st = new Scanner(System.in);

        in = st.next();
        if (in.equals("q")) {

            System.out.println("Your survey was cancelled.\n" + "Thank you for your time.");
            System.exit(0);
        }
        if (abb.equals(states)) {

            for (int i = 0; states[0][i] != null; i++) {
                if (abb.equals(states[0][i])) {
                    for (int state = 1; state <= 100; state++) {

                        System.out.println(states[0][i]);
                    }
                }
            }
        } else {
            System.out.println("You've entered invalid state abbrevation.");
        }
        
        return in;
    }

    private static String[][] readStateFile() throws IOException {

        String states[][] = new String[50][50];

        try {
            FileInputStream fstream = new FileInputStream("states copy.bin");
            DataInputStream inputFile = new DataInputStream(fstream);

            for (int i = 0, j = i + 1; i < 50; i++) {
                states[i][0] = inputFile.readUTF();
                states[i][j] = inputFile.readUTF();
                // System.out.println(states);
            }
            inputFile.close();
            return states;
        } catch (EOFException e) {
            System.out.println("Survey Cancelled");
        }
        return states;
    } ```

【问题讨论】:

    标签: java exception multidimensional-array


    【解决方案1】:

    与其使用多维数组,不如使用 HashMap 更有帮助。

    每个缩写都用作一个键,并且可以使用该键作为查找来找到州的名称。如下图:

    public static void main(final String[] args)
    {
        try
        {
            final Map<String, String> states = readStateFile();
    
            // Display the contents of the file
            // for (final Map.Entry<String, String> s : states.entrySet())
            // {
            //  System.out.println(s.getKey() + " = " + s.getValue());
            // }
    
            final String state = getState(states);
            final int age = getAge();
            final int postalCode = getZIPcode();
    
            System.out.println();
            System.out.printf("Age:\t\t%d\n", Integer.valueOf(age));
            System.out.printf("Address:\t%s %s\n\n", Integer.valueOf(postalCode), state);
            System.out.println("Your survey is complete. Your participation has been valuable.");
        }
        catch (final IOException ex)
        {
            System.out.println(ex.getMessage());
        }
    
        System.out.println("Thank you for your time.");
    }
    
    private static String getState(final Map<String, String> states)
    {
        System.out.println("Please enter the 2 letter state abbrevation or 'q' to quit: ");
        final StringBuilder sb = new StringBuilder();
    
        try (final Scanner st = new Scanner(System.in))
        {
            final String stateAbbrev = st.next().toUpperCase(Locale.getDefault());
            if ("Q".equals(stateAbbrev))
            {
                System.out.println("Your survey was cancelled." + System.lineSeparator() + "Thank you for your time.");
                System.exit(0);
            }
    
            if (states.containsKey(stateAbbrev))
            {
                final String stateName = states.get(stateAbbrev);
                sb.append(stateName);
            }
            else
            {
                System.out.println("You've entered an invalid state abbrevation: " + stateAbbrev);
            }
        }
    
        return sb.toString();
    }
    
    private static Map<String, String> readStateFile() throws IOException
    {
        final List<String> lines = Files.readAllLines(Paths.get("C:/states copy.bin"));
    
        // Get a list of items, with each item separated by any whitespace character
        final String[] stateAbbrev = lines.get(0).split("\\s");
        final String[] stateNames = lines.get(1).split("\\s");
    
        final Map<String, String> states = new HashMap<>();
        for (int i = 0; i < stateAbbrev.length; i++)
        {
            states.put(stateAbbrev[i], stateNames[i]);
        }
    
        return states;
    }
    

    【讨论】:

    • 我只能使用二维数组并使用 try 和 catch 方法。我不能使用 HashMap
    • @Ashish5525 你能使用像 String[] 这样简单的一维数组吗?
    • 不应该有二维数组,因为有 2 行数据。第 1 行包含 2 个字母缩写,第 2 行包含全州名称。
    • 这太可怕了。 (一个二维数组将分配 50x50 个内存位置来存储 50+50 个信息字符串。两个单个数组就足够了。)
    • 我完全理解,但不幸的是这些是说明:(
    猜你喜欢
    • 2018-02-26
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 2015-03-01
    相关资源
    最近更新 更多