从逗号分隔的文本文件中读取数组

时间:2016-03-12 00:29:32

标签: java arrays

想要在逗号分隔的文本文件中打印矩阵,但此代码将打印出矩阵,其中所有零都不是文本文件中的矩阵。

public int[][] readFromFile() throws FileNotFoundException {
    Scanner in = new Scanner(new File("C:\\Users\\Aidan\\Documents\\NetBeansProjects\\matrix\\src\\matrix\\newfile"));
    int[][] a = new int[9][9];
    while (in.hasNext()) {
        String word = in.next();
        if (word.equals(",")) {
            continue;
        }
        System.out.println(word);
        int x = 0;
        int y = 0;
        //System.out.println(Integer.parseInt(word));
        int s = Integer.parseInt(word);
        a[x++][y++] = s;
    }
    return a;
}

1 个答案:

答案 0 :(得分:0)

假设csv文件中有多行:

1,2,3,4,5,6,7,8,9
2,3,4,5,6,7,8,9,1
3,4,5,6,7,8,9,1,2
...

您应该可以执行以下操作:

int[][] a = new int[9][9];
Scanner in = new Scanner(new File("C:\..."));
for (int i = 0; i < 9; i++) {
    String[] line = in.nextLine().split(",");
    for (int j = 0; j < 9; j++) {
        a[i][j] = Integer.parseInt(line[j]);
    }
}

这是最低限度,并且不包括错误检查,如果csv中的行少于9个以逗号分隔的数字,程序将崩溃。

相关问题