Friday, November 18, 2011

Java (The while Loop)

The while Loop


The syntax for the while loop is as follows:
while (loop-continuation-condition) {
  // Loop body
  Statement(s);
}

The while loop flow chart is shown in Figure 4.1(a). The part of the loop that contains the statements to be repeated is called the loop body. A one-time execution of a loop body is referred to as an iteration of the loop. Each loop contains a loop-continuation condition, a Boolean expression that controls the execution of the body. It is always evaluated before the loop body is executed. If its evaluation is true, the loop body is executed; if its evaluation is false, the entire loop terminates and the program control turns to the statement that follows the while loop. For example, the following while loop prints "Welcome to Java!" a hundred times.
int count = 0;
while (count < 100) {
  System.out.println("Welcome to Java!");
  count++;
}



Figure 4.1. The while loop repeatedly executes the statements in the loop body when the loop-continuation-condition evaluates to true.




The flow chart of the preceding statement is shown in Figure 4.1(b). The variable count is initially 0. The loop checks whether (count < 100) is true. If so, it executes the loop body to print the message "Welcome to Java!" and increments count by 1. It repeatedly executes the loop body until (count < 100) becomes false. When (count < 100) is false (i.e., when count reaches 100), the loop terminates and the next statement after the loop statement is executed.

Note


The loop-continuation-condition must always appear inside the parentheses. The braces enclosing the loop body can be omitted only if the loop body contains one or no statement.


Caution


Make sure that the loop-continuation-condition eventually becomes false so that the program will terminate. A common programming error involves infinite loops. That is, the program cannot terminate because of a mistake in the loop-continuation-condition. For instance, if you forgot to increase count (count++) in the code, the program would not stop. To terminate the program, press CTRL+C.


Tip


If you use an IDE such as JBuilder, NetBeans, or Eclipse, please refer to Learning Java Effectively with JBuilder/NetBeans/Eclipse in the supplements. This supplement shows you how to use a debugger to trace a simple loop statement.


4.2.1. Example: An Advanced Math Learning Tool

The Math subtraction learning tool program in Listing 3.5, SubtractionTutor.java, generates just one question for each run. You can use a loop to generate questions repeatedly. Listing 4.1 gives a program that generates ten questions and reports the number of correct answers after a student answers all ten questions. The program also displays the time spent on the test and lists all the questions, as shown in Figure 4.2.


Figure 4.2. (a) The program prompts the user to answer the first question. (b) The program grades the answer. (c) The program displays a summary of the answers.


Listing 4.1. SubtractionTutorLoop.java


 1 import javax.swing.JOptionPane;
 2
 3 public class SubtractionTutorLoop {
 4   public static void main(String[] args) {
 5   int correctCount = 0; // Count the number of correct answers
 6   int count = 0; // Count the number of questions
 7   long startTime = System.currentTimeMillis();
 8   String output = "";
 9
10   while (count < 10) {
11     // 1. Generate two random single-digit integers
12     int number1 = (int)(Math.random() * 10);
13     int number2 = (int)(Math.random() * 10);
14
15     // 2. If number1 < number2, swap number1 with number2
16     if (number1 < number2) {
17       int temp = number1;
18       number1 = number2;
19       number2 = temp;
20     }
21
22     // 3. Prompt the student to answer "what is number1 – number2?"
23     String answerString = JOptionPane.showInputDialog
24       ("What is " + number1 + " - " + number2 + "?");
25     int answer = Integer.parseInt(answerString);
26
27     // 4. Grade the answer and display the result
28     String replyString;
29     if (number1 - number2 == answer) {
30       replyString = "You are correct!";
31       correctCount++;
32     }
33     else
34       replyString = "Your answer is wrong.\n" + number1 + " - "
35         + number2 + " should be " + (number1 - number2);
36       JOptionPane.showMessageDialog(null, replyString);
37
38       // Increase the count
39       count++;
40
41       output += "\n" + number1 + "-" + number2 + "=" + answerString +
42         ((number1 - number2 == answer) ? " correct" : " wrong");
43     }
44
45     long endTime = System.currentTimeMillis();
46     long testTime = endTime - startTime;
47
48     JOptionPane.showMessageDialog(null,
49       "Correct count is " + correctCount + "\nTest time is " +
50       testTime / 1000 + " seconds\n" + output);
51   }
52 }
The program uses the control variable count to control the execution of the loop. count is initially 0 (line 6) and is increased by 1 in each iteration (line 39). A subtraction question is displayed and processed in each iteration. The program obtains the time before the test starts in line 7 and the time after the test ends in line 45, and computes the test time in line 46. The test time is in milliseconds and is converted to seconds in line 50.

4.2.2. Controlling a Loop with a Confirmation Dialog

The preceding example executes the loop ten times. If you want the user to decide whether to take another question, you can use a confirmation dialog to control the loop. A confirmation dialog can be created using the following statement:



When a button is clicked, the method returns an option value. The value is JOptionPane.YES_OPTION (0) for the Yes button, JOptionPane.NO_OPTION (1) for the No button, and JOptionPane.CANCEL_OPTION (2) for the Cancel button. For example, the following loop continues to execute until the user clicks the No or Cancel button.
int option = 0;
while (option == JOptionPane.YES_OPTION) {
  System.out.println("continue loop");
  option = JOptionPane.showConfirmDialog(null, "Continue?");
}

You can rewrite Listing 4.1 using a confirmation dialog to let the user decide whether to continue the next question.

4.2.3. Controlling a Loop with a Sentinel Value

Another common technique for controlling a loop is to designate a special value when reading and processing a set of values. This special input value, known as a sentinel value, signifies the end of the loop.
Listing 4.2 writes a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. Do you need to declare a new variable for each input value? No. Just use one variable named data (line 9) to store the input value and use a variable named sum (line 12) to store the total. Whenever a value is read, assign it to data and added to sum (line 14) if it is not zero.

Listing 4.2. SentinelValue.java

 1 import javax.swing.JOptionPane;
 2
 3 public class SentinelValue {
 4   /** Main method */
 5   public static void main(String[] args) {
 6     // Read an initial data
 7     String dataString = JOptionPane.showInputDialog(
 8       "Enter an int value:\n(the program exits if the input is 0)");
 9     int data = Integer.parseInt(dataString);
10
11     // Keep reading data until the input is 0
12     int sum = 0;
13     while (data != 0) {
14       sum += data;
15
16       // Read the next data
17       dataString = JOptionPane.showInputDialog(
18         "Enter an int value:\n(the program exits if the input is 0)");
19       data = Integer.parseInt(dataString);
20     }
21
22      JOptionPane.showMessageDialog(null, "The sum is " + sum);
23   }
24 }

A sample run of the program is shown in Figure 4.3. If data is not 0, it is added to the sum (line 14) and the next items of input data are read (lines 12–19). If data is 0, the loop body is no longer executed and the while loop terminates. The input value 0 is the sentinel value for this loop. Note that if the first input read is 0, the loop body never executes, and the resulting sum is 0.


Figure 4.3. The program uses a while loop to add an unspecified number of integers.


Caution


Don't use floating-point values for equality checking in a loop control. Since floating-point values are approximations for some values, using them could result in imprecise counter values and inaccurate results. This example uses int value for data. If a floating-point type value is used for data, (data != 0) may be true even though data is exactly 0.
Here is a good example provided by a reviewer of this book:
// data should be zero
double data = Math.pow(Math.sqrt(2), 2) – 2;

if (data == 0)
  System.out.println("data is zero");
else
  System.out.println("data is not zero");

Like pow, sqrt is a method in the Math class for computing the square root of a number. The variable data in the above code should be zero, but it is not, because of rounding-off errors.

No comments:

Post a Comment