Java Reference
In-Depth Information
Place these statements between the
{ }
of the
while
loop.
7.
Remember, you must alter the value of the variable used in the conditional expression during
the loop to avoid infinite looping. You may add it anywhere within the loop, but keep in mind
that the statements are executed from top to bottom, so if you change the value of
i
before dou-
bling and printing, you will double and print the new value. Add the following line after the
System.out.println()
line, but before the next
}
.
i++;
8.
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
while
loop, but before the
closing bracket
(})
of the
main
method. This ensures that it will not be repeated in each iteration,
but it will be executed once before the
main
method concludes.
9.
Your class body should now look like this:
public class WhileLoop {
public static void main(String[] args) {
int i = 1;
while (i <= 10){
int doubled = i * 2;
System.out.println(i + " times two equals " + doubled);
i++;
}
System.out.println("End of program");
}
}
10.
Save the class by clicking the disk icon or selecting File, then Save.
11.
Run the application by clicking the green play icon or selecting Run, and then Run.
How It Works
Now take a look at how it works.
1.
The application begins by executing the
main
method, which in this case is the only method.
2.
The first statement initializes an integer, named
i
, with the value of
1
.
3.
The next statement opens a
while
loop, which will loop based on the value of the integer
i
initial-
ized in the previous statement.
4.
In the first statement inside the loop, a second
int
, named
doubled
, is assigned the value of
i
*2
. In
this first iteration,
i
=1
, so
doubled
=2
.
5.
In the next statement of the loop, there is a
println
command. A line is output to the console
which reads:
1 times two equals 2
. Because the command is
println
instead of
print
, you can
imagine pressing Enter or Return at the end of the string to create a new line.
6.
The last statement inside the
while
loop reassigns the value of
i
to
i
+1
or
i
=2
.
Search WWH ::
Custom Search