Page 158 - Introduction to Programming with Java: A Problem Solving Approach
P. 158
124 Chapter 4 Control Statements
A while loop’s condition is the same as an if statement’s condition. It typically employs comparison
and logical operators, and it evaluates to true or false. Here’s how the while loop works:
1. Check the while loop’s condition.
2. If the condition is true, execute the while loop’s body (the statements that are inside the braces),
jump back to the while loop’s condition, and repeat step 1.
3. If the condition is false, jump to below the while loop’s body and continue with the next statement.
Example
Now let’s consider an example—a program that creates a bridal gift registry. More specifically, the program repeatedly prompts the user for two things—a gift item and the store where the gift can be purchased. When the user is done entering gift and store values, the program prints the bridal registry list. Study this sample session:
Sample session:
Do you wish to create a bridal registry list? (y/n): y
Enter item: candle holder
Enter store: Sears
Any more items? (y/n): y
Enter item: lawn mower
Enter store: Home Depot
Any more items? (y/n): n
Bridal Registry:
candle holder - Sears
Apago PDF Enhancer
lawn mower - Home Depot
That’s the problem specification. Our solution appears in Figure 4.11. As you can tell by
Use I/O sample to specify problem.
the while loop’s more
program employs a user-query loop. The initial query above the while loop makes it pos- sible to quit without making any passes through the loop. If you want to force at least one
pass through the loop, you should delete the initial query and initialize more like this: char more = 'y';
The BridalRegistry program illustrates several peripheral concepts that you’ll want to remember for future programs. Within the while loop, note the += assignment statements, repeated here for your convenience:
registry += stdIn.nextLine() + " - ";
registry += stdIn.nextLine() + "\n";
The += operator comes in handy when you need to incrementally add to a string variable. The Bridal- Registry program stores all the gift and store values in a single String variable named registry. Each new gift and store entry gets concatenated to the registry variable with the += operator.
At the top and bottom of the BridalRegistry program’s while loop, note the nextLine and charAt method calls, repeated here for your convenience:
more = stdIn.nextLine().charAt(0);
The method calls are chained together by inserting a dot between them. The nextLine() method call reads a line of input from the user and returns the input as a string. That string then calls the charAt(0), which returns the string’s first character. Note that it’s acceptable and fairly common to chain multiple method calls together like this.
== 'y' condition and the query at the bottom of the loop, the