简体   繁体   English

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

[英]Reading array from comma separated text file

Want to print out a matrix in a comma separated text file, but this code will print out matrix with all zeroes which is not the matrix in the text file . 想要在逗号分隔的文本文件中打印出矩阵,但是此代码将打印出所有零的矩阵,这些零不是文本文件中的矩阵。

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;
}

Assuming you have multiple lines in your csv file: 假设你的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
...

You should be able to do something like the following: 您应该可以执行以下操作:

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]);
    }
}

This is the bare minimum, and includes no error checking, if a line in your csv has less than 9 comma separated numbers, the program will crash. 这是最低限度,并且不包括错误检查,如果csv中的行少于9个以逗号分隔的数字,程序将崩溃。

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

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