As you saw in Counting with a While Loop,
a while
loop can be used to to make something happen an
exact number of times.
However, this isn't our best choice. while
loops are
designed to keep going as long as something is true. But if we know
in advance how many times we want to do something, Java has a special kind of
loop designed just for making a variable change values: the for
loop.
Type in the following code, and get it to compile. Then answer the questions down below.
import java.util.Scanner; public class CountingFor { public static void main( String[] args ) { Scanner keyboard = new Scanner(System.in); System.out.println( "Type in a message, and I'll display it five times." ); System.out.print( "Message: " ); String message = keyboard.nextLine(); for ( int n = 1 ; n <= 5 ; n = n+1 ) { System.out.println( n + ". " + message ); } } }
for
loops are best when we know in advance how many times we want to do something.
On the other hand, while
loops are best for repeating as long as
something is true:
Type in a message, and I'll display it five times. Message: Hey, hey. 1. Hey, hey. 2. Hey, hey. 3. Hey, hey. 4. Hey, hey. 5. Hey, hey.
Assignments turned in without these things will receive no credit.
n = n+1
do? Remove it and see what happens. (Then put it back.)
int n = 1
do? Remove it and see what happens. (Then put it back.)
Type in a message, and I'll display it ten times. Message: qwerty 2. qwerty 4. qwerty 6. qwerty 8. qwerty 10. qwerty
©2013 Graham Mitchell
This assignment is licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License.