【问题标题】:How to properly print a 2D array to a text file in Java?如何正确地将二维数组打印到 Java 中的文本文件?
【发布时间】:2017-08-27 01:08:24
【问题描述】:

我可以让我的代码在大部分情况下正常工作,并将 3 个 .csv 文件打印到具有正确文件标题的“提交”文件夹中,但是我不知道如何消除末尾的逗号每行数据,我也无法弄清楚如何以相同的逗号分隔方式将 headerValues 写入文本文件的第二行,在逗号之前或之后没有空格。请务必注意,我必须使用 2D 数组中的嵌套 for 循环写入 .csv 文件。

import java.io.*;

public class HW01 {
    public static void main(String args[]) throws IOException {

        // Create a 1D array to hold header labels
        String headerLabels[] =  
            {
             "COURSE ID", "TEAM ID", "STUDENT FIRST NAME",
             "STUDENT LAST NAME", "STUDENT ID", "ASSIGNMENT ID",
             "DATE SUBMITTED", "TIME SUBMITTED", "SUBMITTED BY"
            };

        // Create a 2D array to hold header values
        String headerValues[][] =
            {
            {"CMPS280-01", "Winners03", "Jacob", "Harley", "w0389342", "H03", "8/23/2017", "7:24PM", "Jacob Harley"},
            {"CMPS280-02", "Invokers01", "James", "Brown", "w0479045", "H01", "8/25/2017", "1:14PM", "James Brown"},
            {"SE101-02", "CodeIt00", "Keith", "Dillinger", "w0782345", "S04", "8/25/2017", "1:23AM", "Keith Dillinger"}
            };

        // Create an int to hold number of students
        int students = headerValues.length;

        // Loop to name .csv files
        for (int i = 0; i < students; i++){

            // Create new .csv file and store in SUBMIT folder
            String path = "SUBMIT/"+headerValues[i][0]+"_"+headerValues[i][5]+"_"+headerValues[i][1]+"_"+headerValues[i][4]+".csv";
                File file = new File(path);
                PrintWriter writer = new PrintWriter(file);

            // Print headerLabels and headerValues
            // for each student into .csv files using loops
            for (int j = 0; j < headerValues[i].length; j++){
                writer.print(headerLabels[j] + ",");
                writer.print(headerValues[i][j] + ",");
            }
                writer.close();
        }

    }
 }

【问题讨论】:

  • 到目前为止你尝试过什么?一个简单的if statement 不就行了吗?
  • 好的,所以在我创建了第一个 if 语句之后,我如何只在我的文本文件中向下一行来使用下一个 for 循环

标签: java arrays csv


【解决方案1】:

您需要将最终的 for 循环拆分为 2 个单独的循环 - 一个用于标题,一个用于值。您可以通过仅在索引 j 小于最后一个索引值时打印逗号问题来解决逗号问题。

for (int j = 0; j < headerLabels[i].length; j++){
    writer.print(headerLabels[j]);
    if(j<headerLabels[i].length-1) writer.print(",");
}
writer.println();

for (int j = 0; j < headerValues[i].length; j++){
    writer.print(headerValues[i][j]);
    if(j<headerValues[i].length-1) writer.print(",");
}
writer.println();

【讨论】:

  • 都是在文本文件的一行打印,但是需要把headerValues[i][j]全部打印到第二行
  • 对不起,当然。您需要在每行输出后打印一个换行符。我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
  • 2014-07-29
  • 2014-04-01
  • 1970-01-01
相关资源
最近更新 更多