University of Cincinnati logo and link  
Iterations
 

 

Consider variable scope when designing loops

 
Be careful of the scope of variables defined in a loop.  They are only in scope in the block in which they are defined.  For example, a variable initialized in the initialization section of a for loop will only have scope within the block of that loop.  In other words,

for (int i = 0; i < 5; i++) {
// i is in scope here
}
// i is out of scope here.

With do-while loops, a varaible decalred in the block is not available to the test.  For example, the following loop may not work as expected.

do {
String input = JOptionPane.showInputDialog("Type STOP to stop");
} while (!input.equalsIgnoreCase("STOP"));

The vairable input of type String is not in scope in the while test, because it is outside of the loop's block!