java - 方法 : Taking a text file and storing it in 2d array

标签 java algorithm

我有一个文本文件,我必须将其存储到一个二维数组中,该数组具有 3 列和 numRecords 行,但它是在一个方法中实现的。参数 numRecords 是要从输入文件中读取的值的数量。我得到一个 InputMismatchException,我不知道为什么。任何帮助将不胜感激

public String[][] readFile(File file, int numRecords) throws IOException {

    int numRows = numRecords;
    int numColumns = 3; // column 1 will be age, column 2 will be height, column 3 will be weight
    String[][] data = new String[numRows][numColumns]; 

    try {
        Scanner readFile = new Scanner(file);
        String line = null;
        line = readFile.nextLine().trim();

        while (readFile.hasNextLine()) {
            line = readFile.nextLine();
            String[] str = line.split(",");

            for (String element : str) {            
                element = element + " "; 

                for (int row = 0; row < data.length; row++) {
                    for (int column = 0; column < data[0].length; column++) {

                        data[row][column] = Integer.toString(readFile.nextInt());
                        data[row][column] = Integer.toString(readFile.nextInt());
                        data[row][column] = Integer.toString(readFile.nextInt());
                    }
                } 
            }
        }

        readFile.close();
    }

    catch (InputMismatchException e1) {
        e1.printStackTrace();
    }

    return data;
}

最佳答案

您正在通过读取行​​从您的扫描仪生成元素。您还试图从扫描仪中读取 int(s) 并忽略您已读取的元素。另一个可能的问题是您的代码在开始之前没有测试文件是否可以实际读取。而且我更喜欢 try-with-Resources 而不是显式关闭 Scanner (因为这里只要有异常就会泄漏文件句柄)。另外,为什么读取 int(s) 并将它们转换为 String - 我更喜欢读取 int[][]。把这些放在一起,

public int[][] readFile(File file, int numRows) throws IOException {
    if (!file.exists() || !file.canRead()) {
        System.err.printf("Cannot find file: %s%n", file.getCanonicalPath());
        return null;
    }
    int numColumns = 3; 
    int[][] data = new int[numRows][numColumns];

    try (Scanner readFile = new Scanner(file)) {
        while (readFile.hasNextLine()) {
            String line = readFile.nextLine();
            String[] tokens = line.split(",");
            int row = 0, column = 0;
            for (String element : tokens) {
                if (column >= numColumns) {
                    column = 0;
                    row++;
                }
                data[row][column] = Integer.parseInt(element);
                column++;
            }
        }
    } catch (InputMismatchException e1) {
        e1.printStackTrace();
    }

    return data;
}

关于java - 方法 : Taking a text file and storing it in 2d array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57734539/

相关文章:

algorithm - 按受欢迎程度对歌曲列表进行排序

java - maven默认使用的插件有哪些?

java - 如何限制用户通过在浏览器中输入URL来访问页面?

java - 如何安装JDK和JRE

java - 如何修复 NumberFormatException(来自文本文件输入)?

algorithm - 多边形包含点算法解释

algorithm - 如何在完全二叉树的最后一层中找到最右边的节点的位置?

java - 可运行 Jar 文件中没有此类文件异常

java - 计算二进制字的奇偶校验

algorithm - 预测资源利用率