【问题标题】:Java .csv print statement issueJava .csv 打印语句问题
【发布时间】:2020-06-20 10:05:56
【问题描述】:

目前正在处理一个导入 .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());
    }
}

【问题讨论】:

    标签: java arrays csv multidimensional-array input


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 感谢您的反馈。什么可以代替while (s.hasNext()),所以不要遍历每一行并打印,而只是打印输入的单行。
    • “单行输入”是什么意思?之前你说过你的输入文件有 21 行
    • 确实如此,我的意思是从 csv 文件中只打印一行(行)而不是整个第一列
    • 听起来你想要循环遍历给定行中的字符串(列):for (String theString : myArray[row]) System.out.println(theString);
    【解决方案2】:

    我建议使用 lib 来读取 CSV 文件: https://mkyong.com/java/how-to-read-and-parse-csv-file-in-java/

    import com.opencsv.CSVReader;
    
    import java.io.FileReader;
    import java.io.IOException;
    
    public class CSVReaderExample {
    
        public static void main(String[] args) {
    
            String csvFile = "/Users/mkyong/csv/country3.csv";
    
            CSVReader reader = null;
            try {
                reader = new CSVReader(new FileReader(csvFile));
                String[] line;
                while ((line = reader.readNext()) != null) {
                    System.out.println("Country [id= " + line[0] + ", code= " + line[1] + " , name=" + line[2] + "]");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
    
        }
    
    }
    

    【讨论】:

    • 感谢您的反馈。但我目前正在做的是将文件数据存储到与 main() 不同的类中的数组中。我使用 get 方法拉入 main() 或导入文件一般没有问题。我的问题更多是关于修复我的代码正在提取的特定数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    相关资源
    最近更新 更多