How to Take Input in a Loop in Java
Control loop execution by declaring entrance and exit conditions when the code is written. Make that process dynamic by asking the user to input conditional data at run time. Pass the input variables to the loop's conditional variables and the user takes control of the entry and exit conditions. These standard looping controls take place outside the loop's operation. To control program execution within a loop, code internal input prompts, accept the input and test it against the loop's exit conditions.
Instructions
-
-
1
Define the variable type before entry into the loop. In this example, use a character variable:
char x;
-
2
Prompt the user for input with the statement:
out.println ("Enter a letter or type q to quit: ");
x = input.nextChar();
-
-
3
Start the loop and define the exit condition:
while ( x != "q") {
-
4
Enter something for the loop to do. In this case display the current character and ask for another with the statements:
System.out.println("You entered %d. Enter another letter or type q to quit: " , x);
x = input.nextChar();
-
5
Close the loop with the ending curly brace:
}
-
1
Tips & Warnings
It is imperative to use the three elements shown in this extremely simple example. First, initialize a controlling variable. Next set an entry/exit condition. Finally, accept and evaluate the variable data.
Failing to set an exit condition results in an infinite loop. Always provide users with a clearly labeled exit method.
References
- "Java2: The Complete Reference"; Patrick Naughton and Herbert Schildt; 1999
- Photo Credit Rayes/Lifesize/Getty Images