Java Arena
Step 8 of 9

Records in a file

Most data files hold records: each line describes one thing, with its values separated by a comma. This format is called CSV, short for comma-separated values, and spreadsheet programs can save a sheet in it. Each line is read, split and converted, just as in module 16:

The file rentals.txt
Ilona,3
Marek,1
Sofia,5
import java.nio.file.Paths;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int total = 0;
        int longest = 0;
        String longestName = "";
        try (Scanner scanner = new Scanner(Paths.get("rentals.txt"))) {
            while (scanner.hasNextLine()) {
                String[] parts = scanner.nextLine().split(",");
                String name = parts[0];
                int hours = Integer.valueOf(parts[1]);
                System.out.println(name + ": " + hours + " h");
                total += hours;
                if (hours > longest) {
                    longest = hours;
                    longestName = name;
                }
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
        System.out.println("Total: " + total + " h");
        System.out.println("Longest rental: " + longestName);
    }
}
Output
Ilona: 3 h
Marek: 1 h
Sofia: 5 h
Total: 9 h
Longest rental: Sofia

scanner.nextLine().split(",") reads a line and splits it at once. The parts are Strings, so the hours need Integer.valueOf before they can be added up.

Not every file uses commas. Semicolons are common too, especially where the comma is the decimal separator: then the line is split with split(";"). Look at the file before you write the program.

A header line

A CSV file often starts with a header: a first line that names the columns, such as name,hours. It isn't data, and Integer.valueOf("hours") would fail. Read it before the loop, and don't use it:

try (Scanner scanner = new Scanner(Paths.get("rentals.csv"))) {
    scanner.nextLine(); // skip the header
    while (scanner.hasNextLine()) {
        String[] parts = scanner.nextLine().split(",");
        // ...
    }
}

Lines that don't fit

A line with no comma splits into one part only, and parts[1] throws an exception. Inside the try, that ends the reading. When a file may have such lines, check parts.length first, and skip the line with continue if it has too few parts.

Your task

Challenge 1 of 3

The file stock.txt has lines such as pens;40: an item and how many are left in stock, separated by a semicolon. Fill in the blanks, so the program prints the items that have fewer than 10 left. For the file shown below, it prints:

Low on stock:
glue (4)
tape (0)

Challenge 2

The file order.csv starts with the header line item,quantity,price, and each line after it is one row of an order, such as notebook,3,4: 3 notebooks at 4 euros each. Print each item with its row total (quantity times price), and then the total of the whole order. For the file shown below, the program prints:

notebook: 12
pencil: 5
backpack: 25
Total: 42

Challenge 3

What does this program print? Every line is split, and then each of its parts is added.