It's important for a program to be able to do things repeatedly; for example, a robot must read its sensors repeatedly and react only when certain conditions are met.
- Create a new project folder named LoopExample
- Open the LoopExample folder
- Create a new file (File->New File)
- Cut and paste the following program into the editor:
public class LoopExample { public static void main(String args[]) { int counter; counter = 1; while (counter <= 10) { System.out.println(counter); counter = counter + 1; } } }
- Save the program as LoopExample.java
- Run the program in the debugger with a breakpoint set at the line while (counter <= 10)
- Step through the program a line at a time, observing the program output, variables, and flow of execution
Understanding the program
Our program:
- Creates a loop counter variable
- Initializes the loop counter to 1
- Repeatedly evaluates the expression (counter <= 10) and while the expression evaluates as true
- prints the counter value
- increments the counter value by 1
The result of running the program is that the numbers 1 through 10 are printed. With only 10 iterations of the loop, you might ask whether it might be easier to just print each number manually, but consider a loop that might require thousands of iterations or that might run indefinitely until something happened:
while (distanceToTarget > 0) { driveForward(0.50); distanceToTarget = checkDistance(); }
Java includes three types of loop statements:
- while
- for
- do
Extra credit
- Read more about Java loops
- Re-write the sample program using a do loop
- Re-write the sample program using a for loop
Last modified 6 years ago
Last modified on Nov 4, 2019, 3:37:07 PM