Assignment #63: Counting with a While Loop
Code
/// Name: Kiran O'Farrell
/// Program Name: Counting with a While Loop
/// File Name: CountingWhile.java
/// Date Completed: 1/12/15
import java.util.Scanner;
public class CountingWhile {
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();
int n = 0;
while ( n < 5 ) {
System.out.println( (n+1) + ". " + message );
n++;
}
}
}
Picture of the output
Notes
- "n++" tells the code how many messages it's printed. Removing it makes the loop trigger infinitely, printing infinite messages.
- To make the code print 10 times, change "while (n < 5)" to "while (n < 10)".
- To make the code ask you for the number of messages, create an int variable for the number of repeats. Then, write a line of code asking for a keyboard.nextInt() to set the variable's value. Finally, change "while (n < 5)" to "while (n < repeats)".