Date: Wednesday, February 12, 2020.
Due date: Wednesday, February 19, 2020.
Objective: To use conditionals in Java.
In this project, we will generate a secret number, then ask the user to guess it. Then we will let them know if they guessed or not.
Create a Java project in Eclipse and call it lab5. Create a class in this project called SecretNumber and containing the main method. Write your name, course, semester, and homework number at the top as a comment.
a. Simple output.
Declare two integer variables to hold the secret number and the user's guess. Assign any value you want between 1 and 10 to the secret number variable.
Add the line
import java.util.Scanner;
between the package and the class declarations. Then declare a Scanner variable like usual:
Scanner scan = new Scanner(System.in);
Ask the user to make a guess between 1 and 10, then input an integer value into the variable guess using the method nextInt().
Next, add a conditional that checks if the user's guess with the secret number. If they are equal, output a message letting them know that they guessed it right. If not, output a message letting them know they didn't get it.
b. Case-based output.
Next, we would like to give the user a more explicit message. Thus, in the else of the conditional where the secret number is not equal to the guess, test whether the guess is less than or greater than the secret number. Then output a different message in each case.
c. Randomizing the number.
This game is not very exciting to play if the secret number is always the same every time. Let's add some functionality to randomize it.
At the top of the program, between the package and class declarations, add the following line:
import java.util.Random;
Then inside the main, right after declaring the scanner, add the following line:
Random rand = new Random();
This creates a variable of type random. This allows us to generate pseudo-random numbers in our program. Then before you ask the user for their guess, initialize the variable secret number the following way:
secret = 1 + rand.nextInt(10);
Note: the random function nextInt returns a value between 0 (included) and the argument-1 (included). Thus, nextInt(10) returns a random number between 0 and 9. To make the range 1 to 10 we need to add 1 to it.
To make sure that the program works correctly, in the case where the user has not guessed the number, output the secret number after letting them know that they didn't guess. You will need to add braces around the code in the first else.
Run the program several times to make sure everything works correctly and that you get a different secret number (generally) if you run it again.
Upload SecretNumber.java to Canvas in Assignments - Homework 5, or wait until you have completed the homework to upload both files at the same time.