Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

(Optional) 6.4 Writing files — writing a data set

Lesson

Optional lesson — beyond the AP CS A exam. Writing to files is not on the AP exam (which only reads files); this is here for a fuller picture of Java.

Writing a whole data set

To save a data set, loop over it and write one line per record. A common format is CSV (comma-separated values): each line is the fields joined by commas — the same format you read back with split.


Worked example

String[] names = {"Ada", "Sam", "Kai"};
int[] scores = {88, 91, 75};
PrintWriter out = new PrintWriter(System.out);
for (int i = 0; i < names.length; i++) {
    out.println(names[i] + "," + scores[i]);
}
out.flush();

Each pass writes one CSV line: Ada,88, then Sam,91, then Kai,75.


▶ Try it: run this, then change the data or the separator and re-run.



A CSV line is...


To write a data set, you loop and write...


Type exactly what this program prints.

String[] n = {"Bo", "Cy"};
int[] s = {40, 95};
PrintWriter out = new PrintWriter(System.out);
for (int i = 0; i < n.length; i++) {
    out.println(n[i] + "," + s[i]);
}
out.flush();

CSV is the same format you read back with...


True or false?