[英]How to properly print a 2D array to a text file in Java?
我可以使我的代碼在大多數情況下都能正常工作,並使用正確的文件標題將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();
}
}
}
您需要將final 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.