auprest
auprest

Reputation: 15

Problems Formatting .CSV Output

I am currently programming an assignment for a class of mine. I am trying to print to my output file to a csv file. The problem is, after I end my second print statement, my output doesn't line up after starting the print statement in my while loop.

For example, here is my code:

oFile = new PrintStream(new File("output.csv"));
        oFile.println("First Name" + "," + "Last Name" + "," + "Lecture Section"+","+"Lab Section"+","+"Lab 1"+","+"Lab 2"+","+"Lab 3"+","+"Lab 4"+","+"Lab 5"+","+"Lab 6"+","+"Lab 7"+","+"Lab 8"+","+"Lab 9"+","+"Lab 10");

        loadLectureArray();
        loadLabArray();
        sortClassSections();

        for (int i = 0; i < stud.size(); i++) {
            oFile.println(stud.get(i).getStudFirstName() + ","+stud.get(i).getStudLastName()+","+stud.get(i).getStudLectureNum()+","+stud.get(i).getStudLabNum()+",");

            while (numLab < 10 && i < stud.size()) {
                oFile.println(labStud.get(i).grades.getStudLabGrade()[numLab]);
                numLab++;
            }
            numLab = 0;
        }

After I execute my while loop, my new data is printed in-between my header and other data. Some of the code is not perfect, but currently I am just seeking advice about reformatting my output to line back up with the print statements.

This is my first time exporting a file to csv, so if there is something I am doing wrong or need to change, please let me know! I hope you can make sense out of what I'm trying to ask for. Thanks in advance!

Upvotes: 0

Views: 58

Answers (1)

Sam
Sam

Reputation: 859

well, println always prints a newline, so you get a newline after every grade. you should be able to get what you want using oFile.print(...) instead of oFile.println(...) inside the for loop and just one oFile.println() at the very end of it.

i also noticed that the test for i < stud.size() in the head of the while loop is redundant since nothing should be changing either i or stud.size() between this test and the same test in the head of the for loop.

Upvotes: 2

Related Questions