How to Choose Between a Reading and a Counting Loop
Some loops both count and read. Yet the overall structure of such loops is usually just a counting loop or a reading loop.
For example, if a loop is supposed to read exactly five integers from the user, then the overall structure is a counting loop. The clue here is the phrase "read exactly five" -- the flow of the loop is controlled by the count variable that is counting to five. In the body of the loop a read is performed, but flow of the loop (the number of times the loop is performed) is controlled by the counter.
int value = 0;
int count = 1;
while (count <= 5)
{
value = *** READ A NUMBER HERE, either via Scanner, JOptionPane, or Math.random ****
count++;
}
On the other hand, if a loop is to be written which is supposed to "keep reading numbers from the user until the value 100 is entered, and report a count of the number of values they entered" then this would be a reading loop. The clue here is the phrase "keep reading ... until the value 100 is entered". The values entered by the user determine how many times the loop will be performed. If they enter "16 2 100" then the loop is performed twice, but if they enter "3 10 44 90 22 100" then the loop is performed five times -- the number of times the loop is performed is determined by the input data, not by a counter. In the body of the loop you will need to keep incrementing a counter, but the counter is not controlling the loop.
int count = 0;
int val = *** READ THE FIRST VALUE (either via Scanner, JOptionPane, or Math.random) ***
while (val != 100)
{
count++;
val = *** READ ANOTHER VALUE (either via Scanner, JOptionPane, or Math.random) ***
}
System.out.println("The user entered " + count + " integers.");
Click here for a discussion of the two loops described above.
|