Java Reference
In-Depth Information
If not, you can type it yourself. You do not need the comments denoted with /** or // . In Eclipse, they
appear as blue or green text. Comments are useful for explaining what the code is doing, but are never
compiled or executed by Java.
public class ForLoop {
public static void main(String[] args){
}
}
5. Recall that the main method provides the starting point and ordering for the execution of your pro-
gram. Inside the main method, create a for loop as follows:
for (int i = 1; i <= 10 ; i++){
}
It should be placed after (String[] args){ and before the next } .
6. Now insert the statements that will be executed during each loop. On each iteration, you will mul-
tiply the value of i by 2 (doubling it) and then print a string containing the resulting value to the
console. Use the following statements to do so:
int doubled = i * 2;
System.out.println(i + " times two equals " + doubled);
Place these between the { } of the for loop.
7. Finally, add a print statement to indicate the end of the program. Use the following statement:
System.out.println("End of program");
This time, make sure it is placed after the closing bracket (}) of the for loop, but before the clos-
ing bracket (}) of the main method. This ensures that it will not be repeated on each iteration,
but it will be executed once before the main method concludes.
8. Your class body should now look like this:
public class ForLoop {
public static void main(String[] args){
for (int i = 1; i <= 10; i++){
int doubled = i * 2;
System.out.println(i + " times two equals " + doubled);
}
System.out.println("End of program");
}
}
9. Save the class by clicking the disk icon or selecting File, then Save.
10. Run the application by clicking the green play icon or selecting Run, and then Run.
Search WWH ::




Custom Search