简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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