[英]How to properly print a 2D array to a text file in Java?
I can get my code to work properly for the most part and to print 3 .csv files into the "SUBMIT" folder with the correct file titles, however I can't figure out how to eliminate the commas at the end of each line of data, nor can I figure out how to write the headerValues onto the second line of the text file in the same comma separated manner without spaces before or after the commas. 我可以使我的代码在大多数情况下都能正常工作,并使用正确的文件标题将3个.csv文件打印到“ SUBMIT”文件夹中,但是我不知道如何消除逗号分隔的每一行的末尾数据,也无法弄清楚如何以相同的逗号分隔方式将headerValues写入文本文件的第二行,且逗号前后没有空格。 It's important to note that I have to write to the .csv files with a nested for loop from the 2D array.
重要的是要注意,我必须使用来自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();
}
}
}
You need to split your final for
loop into 2 separate loops - one for the headers and one for the values. 您需要将final
for
循环分为2个单独的循环-一个用于标题,另一个用于值。 You can fix the comma issue by only printing it when the index j
is less than the last index value. 您可以通过仅在索引
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.