Java Arena
Step 5 of 8

The size of a list

size() tells how many values a list holds right now. A new list has size 0, and every add makes it one bigger:

ArrayList<String> guests = new ArrayList<>();
System.out.println(guests.size());
guests.add("Rosa");
guests.add("Tariq");
guests.add("Yuki");
System.out.println(guests.size());
System.out.println("Last to arrive: " + guests.get(guests.size() - 1));
Output
0
3
Last to arrive: Yuki

Since indexes start at 0, the last index is always size() - 1. So guests.get(guests.size() - 1) is the last value, however long the list is. (On an empty list, that's get(-1), which crashes: check that the size is above 0 first.)

Reading an unknown number of values

size() is what makes lists so handy for input: the program reads as many values as it's given, and counts them afterwards.

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String> trees = new ArrayList<>();
        while (true) {
            String tree = scanner.nextLine();
            if (tree.equals("end")) {
                break;
            }
            trees.add(tree);
        }
        System.out.println("Trees seen: " + trees.size());
        if (trees.size() > 0) {
            System.out.println("First: " + trees.get(0));
            System.out.println("Last: " + trees.get(trees.size() - 1));
        }
    }
}
Input
maple
oak
birch
end
Output
Trees seen: 3
First: maple
Last: birch

Checking an index

With size(), a program can check an index before it uses it. An index is valid when it's at least 0 and less than the size:

if (index >= 0 && index < trees.size()) {
    System.out.println(trees.get(index));
} else {
    System.out.println("No tree at index " + index);
}

Your task

Challenge 1 of 3

Fill in the blanks so the program prints how many photos there are, and which one was added last:

Photos: 4
Newest: pier.jpg

Challenge 2

The block party is held in front of the house in the middle of the block. Read the house numbers along the block, in order, one per line, until 0. Keep them in a list. Then print Houses: and how many there are, and on the next line Party at number and the number of the middle house. With an even number of houses, take the later of the two in the middle. When no houses were read, print Houses: 0 and then No party. For the input 101, 103, 105, 107, 109 and 0 the program prints:

Houses: 5
Party at number 105

Challenge 3

A coat check hands out numbered tickets: the first coat gets ticket 1, the second ticket 2, and so on. Read the coats handed in, one per line, until end. Then read a ticket number, and print the coat for that ticket. When there's no coat for the ticket (0, a negative number, or a number past the last coat), print No coat for ticket and the number. For the input green scarf, black coat, red hat, end and 3 the program prints:

Ticket 3: red hat