繁体   English   中英

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

[英]Method: Taking a text file and storing it in 2d array

我有一个文本文件,我必须将其存储到具有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;
}

您正在通过读取行​​从扫描仪生成element 您还试图从扫描仪读取int,而忽略已读取的元素。 另一个可能的问题是,您的代码在启动之前并未测试文件是否可以实际读取。 我更喜欢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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM