如何在Java中正确打印2D数组到文本文件?

时间:2017-08-27 01:08:25

标签: java arrays csv

我可以让我的代码在大多数情况下正常工作,并将3 .csv文件打印到" SUBMIT"具有正确文件标题的文件夹,但我无法弄清楚如何消除每行数据末尾的逗号,也无法弄清楚如何将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();
        }

    }
 }

1 个答案:

答案 0 :(得分:0)

您需要将最终的for循环拆分为两个独立的循环 - 一个用于标题,一个用于值。您可以通过仅在索引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();