Java & J2EE Page 2 - Java Statements |
The first iteration we will look at is called the While Loop. It is your standard loop that can best be described as: while this is true, keep doing this. class CountDown { public static void main(String args[]) { int timer = 10; // Sets initial value of timer to 10 while(timer > 0) { // Says do this while timer > 0 System.out.println(“T minus “ + timer); timer--; // Decrements timer by -1 each loop } } } The above code is a timer, exactly like the one used by NASA. If you ran the program, the following would print to your screen: T minus 10 T minus 9 T minus 8 T minus 7 T minus 6 T minus 5 T minus 4 T minus 3 T minus 2 T minus 1 The code gives the variable timer an initial value of ten and then as it passes through each loop, it decrements the timer's value by one, prints the string “T minus" and appends the current value of timer to it. It does this until the value of timer is no longer greater than 0. Just as a side note, if the value of timer was not greater than 0 to begin with, the program would have skipped the loop altogether.
blog comments powered by Disqus |
|
|
|
|
|
|
|