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

时间:2017-08-26 20:53:36

标签: java arrays csv

我尝试对我的问题进行简单的修复,将数组打印到.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 个答案:

答案 0 :(得分:0)

嵌套循环并不是问题所在。您尝试编写内容的顺序是。我想,您只需要为所有学生提供1个文件,而不是[ERROR] Failed to execute goal on project gameoflife-web: Could not resolve dependencies for project com.wakaleo.gameoflife:gameoflife- web:war:1.0-SNAPSHOT: Could not find artifact com.wakaleo.gameoflife:gameoflife-core:jar:1.0-SNAPSHOT -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException [ERROR] [ERROR] After correcting the problems, you can resume the build with the command [ERROR] mvn <goals> -rf :gameoflife-web Build step 'Invoke top-level Maven targets' marked build as failure Recording test results Publishing Javadoc 个文件。每个学生一个。

例如,

i*j