首页 > 解决方案 > 用文件中的内容填充矩阵

问题描述

我的代码出现错误。目标是将文件的内容添加到矩阵中。然后我最终需要解析它以将其添加到图形中,以便我最终可以对其执行深度优先搜索。但在那之前我需要弄清楚这个错误。我无法弄清楚究竟是什么导致了错误。所以任何帮助都会很好。这是我得到的错误:

Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException
        at java.base/java.util.Scanner.throwFor(Scanner.java:937)
        at java.base/java.util.Scanner.next(Scanner.java:1478)
        at DelivA.<init>(DelivA.java:53)
        at Prog340.actionPerformed(Prog340.java:120

这是我写的课程。

public DelivA(File in, Graph gr) {
        inputFile = in;
        g = gr;
        // Get output file name.
        String inputFileName = inputFile.toString();
        String baseFileName = inputFileName.substring(0, inputFileName.length() - 4); // Strip off ".txt"
        String outputFileName = baseFileName.concat("_out.txt");
        outputFile = new File(outputFileName);
        if (outputFile.exists()) { // For retests
            outputFile.delete();
        }
        try {
            output = new PrintWriter(outputFile);
        } catch (Exception x) {
            System.err.format("Exception: %s%n", x);
            System.exit(0);
        }
        // --------------------------------Deliverable
        // A-------------------------------------------//

        FileReader f1 = null;

        int c = 0;
        int r = 0;
        try {
            f1 = new FileReader(inputFileName);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Scanner scanner = new Scanner(f1);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String splitLine[] = line.split(" ");
            c = splitLine.length;
            r++;
        }
        String[][] matrix = new String[c][r];
        @SuppressWarnings("resource")
        Scanner s1 = new Scanner(f1);
        for (int row = 0; row < matrix.length; row++) {
            String words = s1.next(); // will scan each row of the file
            for (int col = 0; col < matrix[row].length; col++) {
                char ch = words.charAt(col); // will put each character into array
                matrix[row][col] = String.valueOf(ch);
            }
        }
    }

}

标签: javamatrix

解决方案


你的问题可能在这里:

String words = s1.next():

您没有验证是否有可用的线路。

你应该这样做:

...
     Scanner s1 = new Scanner(f1);
            for (int row = 0; row < matrix.length; row++) {
                if (scanner.hasNextLine()){
                    String words = s1.next(); // will scan each row of the file
...

当然,您应该相应地重新考虑代码逻辑...


推荐阅读