gpt4 book ai didi

java - 如何使用嵌套 for 循环将数组值打印到 CSV 文件?

转载 作者:行者123 更新时间:2023-12-02 04:33:48 27 4
gpt4 key购买 nike

我尝试对我的问题进行简单修复,将数组打印到 .csv 文件并替换某些字符,但后来我注意到我不应该在输出中的逗号前后使用任何空格。
我不能使用替换,否则所有标题标签也将有零个空格,因此我需要帮助直接从嵌套的 for 循环中获取值。

import java.io.*;
import java.util.Arrays;

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-02", "Invokers01", "James", "Brown", "w0479045", "H01", "8/25/2017", "1:14PM", "James Brown"},
{"CMPS280-01", "Winners03", "Jacob", "Harley", "w0389342", "H03", "8/23/2017", "7:24PM", "Jacob Harley"},
{"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;

// Array loop to create student .csv files
for (int i = 0; i < headerValues.length; i++){
for (int j = 0; j < students; j++){

// 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
writer.println(Arrays.toString(headerLabels).replace("[", "").replace("]", "").replace(" , " , ","));
writer.println(Arrays.toString(headerValues[i]).replace("[", "").replace("]", "").replace(" , ", ","));
writer.close();
}
}

}
}

最佳答案

嵌套循环并不是问题所在。您尝试编写内容的顺序是。我假设您只需要为所有学生准备 1 个文件,而不是 i*j 文件。每个学生一个。

例如,

    // Create student .csv files and store in SUBMIT folder
String path = "SUBMIT/students.csv";
try (PrintWriter writer = new PrintWriter(new File(path))) {

// Print header row
writer.println(String.join(",", headerLabels));

// Print all data rows
for (String[] studentData : headerValues){
writer.println(String.join(",", studentData);
}
}

关于java - 如何使用嵌套 for 循环将数组值打印到 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45899592/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com