COP 2250Laboratory 4 : Loops – Counters and Flags

Pre-Lab

Create a folder 2250Lab4 on your flash drive. Download theexerciseprogram-stubs.

Exercise 1: Counting

Compile and run Lab04_Exercise1.java. The program goes into an infinite loop.

Eliminate the infinite loop by incrementing the counter. Then change the println() inside the loop to print(): 0 1 2 3 4 5 6 7 8 9 END

Modify the program to count from 1 to 10 instead of from 0 to 9

Modify the program to count in 2’s: 2 4 6 8 10 END

Modify the program to count backwards: 10 9 8 7 6 5 4 3 2 1 END

Exercise 2:Understanding flags

Compile and run Lab04Exercise2.java. The program simulates tossing two 6-sided dice.

Run the program several times to verify that both outputs are always 1 through 6.

Although the program contains a loop to allow several tosses, the loop exits after only a single toss of the two dice. Make sure you understand why.

Change the loop false guard to true, re-compile and run again. Now the program should go into an infinite loop! Make sure you understand why.

The program contains the declaration of a flag, tossDiceAgain, before the loop, and its assignment inside the loop. Un-comment both the declaration and assignment statements, and replace the loop guard with the flag. Re-compile and run again.

Assign the flag so that the loop keeps repeating only if the die faces total 7. Test the program several times until you are sure the flag works correctly.

Assign the flag so that the loop keeps repeating until both die faces are the same (doubles – 1 : 1, or 2 : 2, or 3 : 3, etc.) Test the program several times.

Assign the flag so that the loop keeps running until the die faces are both 6 – 6 : 6! Test the program several times.

Comment the declaration of the flag before the loop; instead, declare and initialize it inside the loop: boolean tossDiceAgain = false; You should have a compile error that relates to the scope of the declaration. Make sure you understand why, then fix the program to make it work correctly again.

Exercise 3: Using a flag

Compile and run Lab04Exercise3.java.The program prompts for a name, and composes a Happy Birthday chorus using the input name. The program then displays the chorus and prompts the user to continue, but ignores the user’s answer; so only one chorus is displayed. The value of answer returned by JOptionPane.ShowConfirmDialog() is either

JOptionPane.YES_OPTIONor JOptionPane.NO_OPTION

Modify the program to allow it to display multiple choruses. Use a flag to control repetition of the loop using the value of answer.