6.3 Event-Controlled Looping

The while loop is used when we don’t know how many times the loop will execute; that is, when the loop begins, we don’t know how many iterations of the loop will be required. We rely on a signal, or event, to tell us that we have processed all the data. For example, when the cashier begins checking out an order, she doesn’t (necessarily) know how many items are in the grocery cart; she only knows to stop when she sees the divider bar on the conveyor belt. We call this an event-controlled loop because we continue processing data until an event occurs, which signals the end of the data.

When we’re prompting the user to enter data from the console, and we don’t know at the beginning of the loop how much data the user ...

Get Java Illuminated, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.