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);
}
}
apple
pear
plum
endWords: 3count++ 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.