Workshop 2007 JRE Java Support
Installation
Home
CalcTool
Java Applets
Friends/Family
Gardening
Woodworking
Forums

For Loops

There are several kinds of loops in java—the for loop, a while loop, and a do-while loop. We’ll focus on the for loop.  More information about the others can be found in here. The basic format for a for loop is

 

for  (initial counter value; logical statement; increment){
      //put code here
}

 

Example:

for (int counter=1; counter<=10; counter++){
      //Put code here
}

 

This is a loop with an initial counter value of counter=1, a logical statement of counter<=10 (this causes the loop to run until counter has exceeded 10), and an increment of counter++ which increments the integer variable counter by 1 after each pass through the loop.

 

Observations.

 

 

 

You try it...

  1. Write a loop that will add up the numbers one through 10 and store the answer in the integer variable answer when clicking computeButton.

 

  1. Output your answer to loopLabelYou must use the setText(String) method to output to loopLabel.  Since this method requires a String as an argument, you must convert answer to String.  The easiest way to do this is to append it to another String with the + operator.  In the context of the setText(String) method, Java will force the type of the appended String and int to be a String.  

 

  1. Build and run your applet. If you’ve done everything correctly, your result should be 55.

 

See Sample Code 1 to check work.

 

 

Loops