首页 > 解决方案 > Java .csv 打印语句问题

问题描述

目前正在处理一个导入 .csv 文件(21 行,20 列)的项目,将其捕获到一个数组中,然后在电子表格中打印一个特定的单元格......目前遇到一个导致输出为 20 的问题行和一列,“null”除了输出中的第二行似乎是文件中的最后一行,第二列单元格。Null 发生了什么,为什么它会提取最后一行数据?谢谢,伙计们/姑娘们的任何意见。

public class cvsPull {

    public String[][] myArray;
    String csvFile = "Crime.csv";

    public Class csvPull() {


    myArray = new String[20][20];


    try {
        s = new Scanner (new BufferedReader(new FileReader(csvFile)));

        while (s.hasNext()) {
            int theRow = 1;
            int theCol = 0;
            InputLine = s.nextLine();
            String[] InArray = InputLine.split(",");

            for (String InArray1 : InArray) {
                myArray[theRow][theCol] = InArray1;
                theCol++;
                if (theCol==20) {
                   theCol=0;
                   theRow++;
                }
             // System.out.println(myArray[theRow][theCol]);

             }

        } 
        for (String[] theString : myArray) {
            System.out.println(theString[1]);
        }
    } catch (IOException ioe) {
        System.out.println("incorrect file name" + ioe.getMessage());
    }
}

标签: javaarrayscsvmultidimensional-arrayinput

解决方案


您在每个循环开始时将行计数器重置为 1:

    while (s.hasNext()) {
        int theRow = 1;
        int theCol = 0;

这意味着文件的每一行都被写入内存中的同一位置。此外,行的第一个索引是 0 就像列一样,因此您最初需要将其设置为 0:

    int theRow = 0;
    while (s.hasNext()) {
        int theCol = 0;

推荐阅读