方法:获取文本文件并将其存储在2d数组中

时间:2019-08-31 01:14:55

标签: java algorithm

我有一个文本文件,我必须将其存储到具有3列和numRecords行的2d数组中,但是是在方法中实现的。参数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;
}

1 个答案:

答案 0 :(得分:0)

您正在通过读取行​​从扫描仪生成element。您还试图从扫描仪读取int,而忽略已读取的元素。另一个可能的问题是,您的代码在启动之前并未测试文件是否可以实际读取。而且我更喜欢try-with-Resources而不是显式关闭Scanner(因为在这种情况下,只要有异常,您就会泄漏文件句柄)。另外,为什么要读取int并将其转换为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;
}