THINK FIRST·CODE LATER

← All labs

Write a file, then read it back

Problem

Write CityLog in two steps:

  1. static int save(Scanner in) throws FileNotFoundException reads city celsius pairs from the keyboard until the end of input and writes them with a PrintWriter to readings.txt (do not forget close()); it returns how many it wrote.
  2. static void report() throws FileNotFoundException opens the file with new Scanner(new File("readings.txt")) and prints each line as %-10s %6.1f C %6.1f F, then Average 19.5 C, hottest Wuhan, coldest Harbin.

main prints Saved 4 readings to readings.txt, calls report(), catches FileNotFoundException, and deletes the file in a finally block.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l17-5-data-1.txt

Wenzhou 24.5
Harbin 3
Wuhan 31.5
Kunming 19
What your program must print for l17-5-data-1.txt
Saved 4 readings to readings.txt
Wenzhou      24.5 C   76.1 F
Harbin        3.0 C   37.4 F
Wuhan        31.5 C   88.7 F
Kunming      19.0 C   66.2 F
Average 19.5 C, hottest Wuhan, coldest Harbin

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l17-5-data-1.txt

Windows PowerShell does not understand <:

Get-Content l17-5-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.