Java Arena
Step 2 of 7

Remembering between commands

The info desk answers every command the same way, whatever came before it. Most programs have to remember something from one command to the next: a count, a total, the names typed so far. Variables do that, with one rule: a variable that must last from command to command is created before the loop. A variable created inside the loop's braces is made new in every round and forgotten at the end of it.

A musician logs practice sessions. log is followed by a line with the minutes practiced, total adds up all the sessions, and longest finds the longest one:

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

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Integer> sessions = new ArrayList<>();
        while (true) {
            System.out.print("> ");
            String command = scanner.nextLine();
            if (command.equals("quit")) {
                System.out.println("Keep practicing!");
                break;
            }
            if (command.equals("log")) {
                int minutes = Integer.valueOf(scanner.nextLine());
                sessions.add(minutes);
                System.out.println("Logged " + minutes + " minutes");
            } else if (command.equals("total")) {
                int total = 0;
                for (int minutes : sessions) {
                    total = total + minutes;
                }
                System.out.println("Total: " + total + " minutes");
            } else if (command.equals("longest")) {
                int longest = 0;
                for (int minutes : sessions) {
                    if (minutes > longest) {
                        longest = minutes;
                    }
                }
                System.out.println("Longest: " + longest + " minutes");
            } else {
                System.out.println("Unknown command: " + command);
            }
        }
    }
}
Input
log
25
log
40
total
log
15
longest
quit
Output
> Logged 25 minutes
> Logged 40 minutes
> Total: 65 minutes
> Logged 15 minutes
> Longest: 40 minutes
> Keep practicing!
  • sessions is created before the loop, so every round adds to the same list, and total sees every session logged so far. Created inside the loop, it would start empty in every round, and total would always say 0 minutes.
  • log reads the minutes from the line after the command, as the previous step described: Integer.valueOf(scanner.nextLine()).
  • total and longest are created inside their own branches. They're only needed while that one answer is worked out, so they're worked out again from the list each time.

Small solutions, put together

The program looks long, but each part of it is something you've written before:

  1. Read commands until quit, and answer unknown ones: the loop of the previous step.
  2. Remember each session: add it to a list.
  3. Add up the values of a list.
  4. Find the largest value of a list.

That's a good way into any bigger program: list the small problems it's made of, solve them one at a time, and try each one before going on. Here you could first write the loop with only quit and the unknown-command answer, then log and total, and longest last. Each piece stays small enough to check at a glance.

What to remember

Remember what later commands need. A list of sessions is one way to do it. But total and longest could also be answered with two int variables, updated at every log, without keeping the sessions at all. A list is needed when a command needs every value again, for example to print all the sessions. Step 5 comes back to this choice.

Your task

Challenge 1 of 3

A small campsite has 3 tent spots. The program remembers how many spots are taken, starting from 0. Create that variable before the loop, and add the commands:

  • arrive: a group arrives. Print Welcome! Free spots: and the number of spots still free, or Sorry, the campsite is full when all 3 spots are taken.
  • depart: a group leaves. Print Safe travels! Free spots: and the number of free spots, or Nobody is camping when no spot is taken.
  • spots: print Free spots: and the number of free spots.
  • Anything else: print Unknown command: and the command.

quit is ready. For the input shown, the program prints:

> Welcome! Free spots: 2
> Welcome! Free spots: 1
> Free spots: 1
> Welcome! Free spots: 0
> Sorry, the campsite is full
> Safe travels! Free spots: 1
> Lights out

Challenge 2

A birdwatcher notes each bird seen. Write the program. Keep the sightings in a list of Strings, one entry for each bird seen, and create the list before the loop. The commands:

  • saw: the next line is a species. Add it to the list and print Noted: and the species.
  • count: the next line is a species. Print the species, : and how many times it was seen, spelled exactly the same, capitals included, like robin: 2.
  • total: print Birds seen: and the number of sightings.
  • quit: print Happy birding! and end the program.
  • Anything else: print Unknown command: and the command.

Print the prompt > before each command. For the input shown, the program prints:

> Noted: robin
> Noted: heron
> Noted: robin
> robin: 2
> owl: 0
> Birds seen: 3
> Happy birding!

Challenge 3

At a deli counter, customers take their place in line and are served in the order they came. Write the program. Keep the names of the waiting customers in a list, first in line first. The commands:

  • take: the next line is a name. Add it to the end of the line, and print the name, , you're number and their place in line, like Ana, you're number 1.
  • next: print Now serving and the first name in line, and take it off the line. If nobody is waiting, print Nobody is waiting.
  • queue: print In line: and the list, like In line: [Ben, Cleo].
  • close: print Closed for today and end the program.
  • Anything else: print Unknown command: and the command.

Print the prompt > before each command. For the input shown, the program prints:

> Ana, you're number 1
> Ben, you're number 2
> Now serving Ana
> Cleo, you're number 2
> In line: [Ben, Cleo]
> Now serving Ben
> Now serving Cleo
> Nobody is waiting
> Closed for today