Java Reference
In-Depth Information
Your First while Loop
try it out
 To create a while loop, follow these steps:
1. Create a new class named WhileLoop , following the same process. You can continue to use the
same Chapter5 project. Create a new class by right-clicking on the src folder in your project.
Select New and then Class.
2. In the Name field, enter the name of your class, WhileLoop, beginning with a capital letter by
Java convention. In the bottom portion of the New Java Class window, there is a section that
reads: “Which method stubs would you like to create?” You may choose to check the box next to
" public static void main(String[] args)" to automatically create a main method.
3. You should automatically have the basis for the class body shown here:
public class WhileLoop {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
If not, you can type it yourself. You do not need the comments, which are denoted with /** or // .
In Eclipse, they will 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 WhileLoop {
public static void main(String[] args){
}
}
4. Recall that the main method provides the starting point and ordering for the execution of your pro-
gram. A while loop requires a variable to be initialized before the loop so that it can be evaluated as
part of the conditional expression. Initialize an integer with the following statement:
int i = 1;
It should be placed after (String[] args){ and before the next } .
5. Now add the following while loop immediately following the int declaration.
while (i <= 10){
}
6. Now insert the statements that will be executed during each loop. In each iteration, you multiply
the value of the current array entry by 2 (doubling it) and then print a string containing the result-
ing value to the console. Use the following statements to do so:
int doubled = i * 2;
System.out.println(i + " times two equals " + doubled);
Search WWH ::




Custom Search