Java Arena
Step 3 of 5

Counting in a loop

To count something in a loop, create a counter before the loop, starting at 0, and add one to it inside the loop each time the thing happens. After the loop, the counter holds the total.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int count = 0;
        while (true) {
            String word = scanner.nextLine();
            if (word.equals("end")) {
                break;
            }
            count++;
        }
        System.out.println("Words: " + count);
    }
}
Input
apple
pear
plum
end
Output
Words: 3

count++ is Java's shorthand for count = count + 1. There's also count--, which takes one away.

Where the counter goes

The counter must be created before the loop. Created inside it, it would start again from 0 in every round, and it could never count past 1. The first challenge has exactly this mistake.

Your task

Challenge 1 of 3

This program should count the words before end, but it always prints Words: 0. Move the counter so it works. For the input red, green, blue and end the program prints:

Words: 3

Challenge 2

The secret number is 42. Read guesses until one is right, then print how many guesses it took, the right one included. For the input 10, 50 and 42 the program prints:

You needed 3 guesses

Challenge 3

Read the lowest temperature of each day until -99. Print how many days had frost (below 0). For the input 3, -2, 0, -7 and -99 the program prints:

Frost days: 2