Question: JAVA PROGRAM: The goal of this exercise is to program a Guess My Number game. When its nished, it will work like this: I'm thinking

JAVA PROGRAM:

The goal of this exercise is to program a Guess My Number game. When its nished, it will work like this:

I'm thinking of a number between 1 and 100

(including both). Can you guess what it is?

Type a number: 45

Your guess is: 45

The number I was thinking of is: 14

You were off by: 31

To choose a random number, you can use the Random class in java.util.

Heres how it works:

import java.util.Random; public class GuessStarter { public static void main(String[] args) {

// pick a random number

Random random = new Random();

int number = random.nextInt(100) + 1;

System.out.println(number);

} }

Like the Scanner class we saw in this chapter, Random has to be imported before we can use it. And as we saw with Scanner, we have to use the new operator to create a Random (number generator). Then we can use the method nextInt to generate a random number. In this example, the result of nextInt(100) will be between 0 and 99, including both. Adding 1 yields a number between 1 and 100, including both.

1. The denition of GuessStarter is in a le called GuessStarter.java, in the directory called ch03, in the repository for this book. 2. Compile and run this program. 3. Modify the program to prompt the user, then use a Scanner to read a line of user input. Compile and test the program. 4. Read the user input as an integer and display the result. Again, compile and test. 5. Compute and display the dierence between the users guess and the number that was generated.

// Explain at the end

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!