您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
Content Page # 6

Iteration: WHILE with compound statements

In just the same way thatifandif...elsecan be used with compound statements, so can while. In the example below a variable counter is initialized, and the statements performed in thewhilestatement display the value of the counter and increment (increase the value of) the counter each time the test is true, until the counter reaches a value of 5:

counter = 0;

while( counter < 5 )

  {

  System.out.println( counter );

  counter = counter + 1;

  }

The output from this piece of code is (the listing of WhileExample.java, containing this code is available for viewing etc.)
 

The reason that the number 5is not printed on screen, is that when the variable counterhas the value5, the test ( counter < 5 ) is false, so the loop is exited, and the statement System.out.println( counter );never executed with counterequal to5.
 

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg