Using Text Files FRQ Practice

Responses receive AI feedback against a rubric after submission. Scores are practice estimates.

Question 1 of 5

Fogbank Observatory stores one integer per token in mist.txt. Write sumMist so it compiles, reads every int with a hasNext loop, and returns the total. The file name is the parameter path.

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Fogbank {
    public static int sumMist(String path) /* header continues */ {
        /* write the method */
    }
}

Question 2 of 5

Quarrywick trucks write each load as one comma token with no spaces, such as 40,2. Trace this code for a file whose tokens are 40,2 then 15,1.

Scanner in = new Scanner(new File("loads.txt"));
int crates = 0;
int trucks = 0;
while (in.hasNext()) {
    String row = in.next();
    String[] parts = row.split(",");
    crates += Integer.parseInt(parts[0]);
    trucks++;
}
in.close();
System.out.print(crates + ":" + trucks);

(a) State the displayed text. (b) Why is split(",") appropriate here instead of a regex character class? (c) Why does this code use next rather than nextLine together with nextInt?

Question 3 of 5

Lumenwick Gallery stores shutter flags in shutters.txt as boolean tokens. Write countOpen(String path) that returns how many tokens are true. Include the needed throws clause and close the Scanner.

Question 4 of 5

A method already read one token into String line. The token uses spaces, for example "7 2 9". Write parseTriple that returns the sum of the three integers using split(" ").

public static int parseTriple(String line) {
    /* write the body */
}

Question 5 of 5

Tidechart Archive keeps yesterday's readings in tides.txt after last night's program ended.

(a) Why can this morning's program still read tides.txt? (b) Write the two java.io import lines needed to construct File and declare IOException. (c) If the pathname is misspelled, what happens when new Scanner(new File(path)) runs in a method that throws IOException and does not catch it?