Dana Vrajitoru
C101 Computer Programming

C101/I210 Homework 6

Due date: Wednesday, February 26, 2020.

Objective: To use the while loop in Java.

Ex. 1. Magic 8 Ball

In this project, we will simulate magic 8 ball using random numbers. We will also let the user enter multiple questions until they decide to quit.

Create a Java project in Eclipse and call it hw6. Create a class in this project called MagicBall and containing the main method. Write your name, course, semester, and homework number at the top as a comment.

a. Setup. Copy both import statements from the lab and the declarations of the variables scan and rand. Declare three variables: one of type String to hold a question asked by the user, and two of type int, one for playing again, and one for the answer given by the magic ball. Initialize the variable to play again as 1.

b. Play. Add a while loop to your code that keeps going while the variable to play again is equal to 1. In the loop, ask the user to ask the magic 8 ball a question. Then read the answer into the variable question using scan.nextLine().

Generate a random number between 0 and 7 and store it in the variable answer. Then add a conditional where you test the value of the answer. If the answer is 0, output something like "Yes". If the answer is 1, then answer something like "You can count on it". And so on for each of the values from 0 to 7. Make sure to include the answer "no", "maybe", and "try again later" in the possible outputs.

c. Play again. Finally, after the conditional, ask the user if they want to ask another question, and to answer 0 for no and 1 for yes, like in the lab. Input the answer into the variable to play again. Then to clear the remaining of the line, repeat the statement that inputs the question as a line.

After the loop, output a goodbye statement, to be polite.

Add a few examples of running the program as comments at the end of the code.

Turn in:

Upload the lab and homework .java files: GuessNumber.java and MagicBall.java, to Canvas in Assignments - Homework 6.