Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Thinking in Java
Prev Contents / Index Next

Iteration

Looping is controlled by while, do-while and for, which are sometimes classified as iteration statements. A statement repeats until the controlling Boolean-expression evaluates to false. The form for a while loop is

while(Boolean-expression)
  statement


The Boolean-expression is evaluated once at the beginning of the loop and again before each further iteration of the statement.

Here’s a simple example that generates random numbers until a particular condition is met:

//: c03:WhileTest.java
// Demonstrates the while loop.
import com.bruceeckel.simpletest.*;

public class WhileTest {
  static Test monitor = new Test();
  public static void main(String[] args) {
    double r = 0;
    while(r < 0.99d) {
      r = Math.random();
      System.out.println(r);
      monitor.expect(new String[] {
        "%% \\d\\.\\d+E?-?\\d*"
      }, Test.AT_LEAST);
    }
  }
} ///:~


This uses the static method random( ) in the Math library, which generates a double value between 0 and 1. (It includes 0, but not 1.) The conditional expression for the while says “keep doing this loop until the number is 0.99 or greater.” Each time you run this program, you’ll get a different-sized list of numbers.

In the expect( ) statement, you see the Test.AT_LEAST flag following the expected list of strings. The expect( ) statement can include several different flags to modify its behavior; this one says that expect( ) should see at least the lines shown, but others may also appear (which it ignores). Here, it says “you should see at least one double value.”
Thinking in Java
Prev Contents / Index Next


 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire