(Homework Solution): Question: Topics This assignment will give you practice with while loops and pseudorandom numbers. Instruct…

Topics

This assignment will give you practice with while loops and pseudorandom numbers.

Instructions

You are going to write a program that allows the user to play a guessing game in which your program “thinks up” an integer and allows the user to make guesses until the user gets it right with cues that indicate whether the secret number is higher or lower than each guess.

Methods

At a minimum, your program should have the following static methods in addition to method main:

a method that introduces the game to the user

a method to play one game with the user (just one game, not multiple games)

a method to report overall results to the user

You may define more methods than this if you find it helpful, although you will find that the limitation that methods can return only one value will tend to limit how much you can decompose this problem.

Max Guess

You are to define a class constant for the maximum number used in the guessing game.

The sample output shows the user making guesses from 1 to 100, but the choice of 100 is arbitrary. By introducing a constant for 100, you should be able to change just the value of the constant to make the program play the game with a range of 1 to 50 or a range of 1 to 250 or some other range starting with 1.

Playing again

When you ask the user whether or not to play again, you should use the “next()” method of the Scanner class to read a one-word answer from the user.

You should continue playing if this answer begins with the letter “y” or the letter “Y”. Notice that the user is allowed to type words like “yes”. You are to look just at the first letter of the user’s response and see whether it begins with a “y” or “n” (either capitalized or not) to determine whether to play again.

Assume Good Input

Assume that the user always types an integer when guessing, that the integer is always in an appropriate range and that the user gives you a one-word answer beginning with “y”, “Y”, “n” or “N” when asked whether to play again.

End statistics

You will notice at the end of the output that you are to report various statistics about the series of games played by the user. You are to report

the total number of games played,

the total number of guesses made (all games included),

the average number of guesses per game, and

the best (fewest) number of guesses used in any single game.

The average number of guesses per games should be rounded to one decimal place (use printf).

Hints

Here are a few helpful hints to keep in mind.

To deal with the yes/no response from the user, you will want to use some of the String class methods.

You should use the next() method of the Scanner class to read a word from the console.

It’s a good idea to change the value of your class constant and run the program to make sure that everything works correctly with the new value of the constant. For example, turn it into a guessing game for numbers between 1 and 5.

While you are developing your program, you might want to have it print out the answer before the user begins guessing. You don’t want this in the final version of the program, but it can be helpful for you while you are developing the code.

Other Details

You should handle the case where the user guesses the correct number on the first try. Print the following message: You got it right on the first guess!!

In the last program you were asked to write very short methods that were no longer than 15 lines long and to have a very short main. This program is more difficult to decompose into methods, so you may end up having methods that are longer than 15 lines.

You can also include more code in your main method than we allowed in the last program. In particular, you are required to have a while loop in main that plays multiple games and prompts the user for whether or not to play another game. Though, you shouldn’t have all of the code in main because you are required to have the methods described at the beginning of this write-up.

You are once again expect you to use good programming style:

Include useful comments throughout your program.

Make appropriate choices about when to store values as int versus double, which if/else constructs to use, what parameters to pass, and so on.

Use whitespace and indentation properly.

Limit lines to 100 characters.

Give meaningful names to methods and variables, and follow Java’s naming standards.

Localize variables whenever possible.

Restrictions

Some students try to achieve repetition without properly using while loops, by writing a method that calls itself; this is not appropriate on this assignment and will result in a deduction in points

You also should not use more advanced topics that we have not covered in class. e.g. No use of Arrays, Lists, Classes

Sample Output

User input is displayed between __ double underscores __ so that you can tell what output is generated by the program and what is input by the user. Your program output will not include these underscores.

This program allows you to play a guessing game.
I will think of a number between 1 and 100 
and will allow you to guess until you get it.  
For each guess, I will tell you whether the right 
answer is higher or lower than your guess.

I'm thinking of a number between 1 and 100...
Your guess? __50__
It's lower.
Your guess? __25__
It's lower.
Your guess? __12__
It's lower.
Your guess? __6__
You got it right in 4 guesses
Do you want to play again? y

I'm thinking of a number between 1 and 100...
Your guess? __50__
It's lower.
Your guess? __25__
It's lower.
Your guess? __12__
It's higher.
Your guess? __18__
You got it right in 4 guesses
Do you want to play again? YES

I'm thinking of a number between 1 and 100...
Your guess? __50__
It's higher.
Your guess? __75__
It's lower.
Your guess? __62__
It's higher.
Your guess? __68__
It's lower.
Your guess? __65__
It's higher.
Your guess? __66__
It's higher.
Your guess? __67__
You got it right in 7 guesses
Do you want to play again? nope

Game statistics:
    total games   = 3
    total guesses = 15
    guesses/game  = 5.0
    best game     = 4

I have done the coding, please check how and correct my code. Please dont use any other methods from higher chapters.

My sample code;

import java.util.*;
// For Scanner and Random numbers
public class guessingGame {

public static final int maxNum = 100;

public static void main(String[] args) {
Random rand = new Random(); //Calling Random
Scanner console = new Scanner(System.in); //Calling Scanner

intro();
OneGame(rand, console);
//game(rand, console);
//determine(int computerNum ,int userGuess);

/*
System.out.println(“I’m thinking of a number between 1 and “+maxNum+”…”);
int computerNumber = rand.nextInt(maxNum) + 1;
int totalGuess = 0;
System.out.print(“Your guess? “);
int userGuess = console.nextInt();
int numOfguess = 1;
if (userGuess == computerNumber) {
System.out.println(“You got it right on the first guess.”);
}
else {
while (userGuess != computerNumber) {
//countUserGuess++;
int rightGuess = determine(computerNumber, userGuess);
if (rightGuess < 0) {
System.out.println(“It’s lower.”);
}
else if (rightGuess > 0) {
System.out.println(“It’s higher.”);
}
System.out.print(“Your guess? “);
userGuess = console.nextInt();
numOfguess++;
}
totalGuess += numOfguess;

System.out.println(“You got it right in “+numOfguess+” guesses”);

}

}
*/
}

// Method to introduce the user with the game.
public static void intro() {
System.out.println(“This program allows you to play a guessing game.”);
System.out.println(“I will think of a number between 1 and 100 intr”);
System.out.println(“and will allow you to guess until you get it.”);
System.out.println(“For each guess, I will tell you whether the right”);
System.out.println(“answer is higher or lower than your guess.”);

}

//Method to play one game
/*public static int game(Random rand, Scanner console) {
System.out.println(“I’m thinking of a number between 1 and 100…”);
int computerNumber = rand.nextInt(100) + 1;
System.out.print(“Your guess? “);
int userGuess = console.nextInt();
int countUserGuess = 1;
while (userGuess != computerNumber) {
int rightGuess = determine(computerNumber, userGuess);
countUserGuess++;

}
System.out.println(“You got it right in “+countUserGuess+” guesses”);
}
*/

public static int determine (int compNum,int userG) {
int rightGuess = 0;
if (userG < compNum) {

rightGuess = -1;
} if (userG > compNum) {

rightGuess = 1;
}// else {
//return countUserGuess++;
//}

return rightGuess;
}

public static int OneGame(rand, console) {
System.out.println(“I’m thinking of a number between 1 and “+maxNum+”…”);
int computerNumber = rand.nextInt(maxNum) + 1;
int totalGuess = 0;
System.out.print(“Your guess? “);
int userGuess = console.nextInt();
int numOfguess = 1;
if (userGuess == computerNumber) {
System.out.println(“You got it right on the first guess.”);
}
else {
while (userGuess != computerNumber) {
//countUserGuess++;
int rightGuess = determine(computerNumber, userGuess);
if (rightGuess < 0) {
System.out.println(“It’s lower.”);
}
else if (rightGuess > 0) {
System.out.println(“It’s higher.”);
}
System.out.print(“Your guess? “);
userGuess = console.nextInt();
numOfguess++;
}
totalGuess += numOfguess;

System.out.println(“You got it right in “+numOfguess+” guesses”);
}

}
/*
public static int loop (int comp, int user) {
while (userGuess != computerNumber) {
//countUserGuess++;
int rightGuess = determine(computerNumber, userGuess);
if (rightGuess < 0) {
System.out.println(“It’s lower.”);
}
else if (rightGuess > 0) {
System.out.println(“It’s higher.”);
}
System.out.print(“Your guess? “);
userGuess = console.nextInt();
numOfguess++;
}

}
*/

}

Expert Answer

answers

Here is the completed and corrected your code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// guessingGame.java

import java.util.*;

public class guessingGame {

// defining all required variables needed throughout the program

public static final int maxNum = 100;

static Random random = new Random();

static Scanner scanner = new Scanner(System.in);

/**

* method to print an intro message to the user

*/

public static void intro() {

System.out.println(“This program allows you to play a guessing game.”);

System.out.println(“I will think of a number between 1 and ” + maxNum);

System.out.println(“and will allow you to guess until you get it. “);

System.out.println(“For each guess, I will tell you whether the right”);

System.out.println(“answer is higher or lower than your guess.nn”);

}

/**

* method to generate a random number between 1 and maxNum

*

@return the generated number

*/

static int generateRandomValue() {

int num = random.nextInt(maxNum) + 1;

return num;

}

/**

* method to play the guess game for once.

*

@return the number of guesses/attempts needed for the user to find the

*         secret number

*/

public static int oneGame() {

// generating secret number and storing in a variable

int secretNum = generateRandomValue();

// displaying a message

System.out.println(“I’m thinking of a number between 1 and ” + maxNum

+ “…”);

int userGuess = -1;

int attempts = 0;

// looping until user enters the correct number

while (userGuess != secretNum) {

System.out.print(“Your guess: “);

// getting guess

userGuess = scanner.nextInt();

attempts++; // incrementing number of guesses

// checking if user guessed correctly

if (userGuess == secretNum) {

// end of loop

break;

else if (userGuess > secretNum) {

// user guess is higher than actual number

System.out.println(“It’s lower.”);

else {

// user guess is lower than actual number

System.out.println(“It’s higher.”);

}

}

// after exiting loop, checking if user guessed it in 1 attempt

if (attempts == 1) {

// displaying special message

System.out.println(“You got it right on the first guess!!”);

else {

// more than one attempt

System.out.println(“You got it right in ” + attempts + ” guesses!”);

}

// returning number of guesses needed

return attempts;

}

/**

* method to print final game stats

*

@param numGames

*            number of games played

@param numGuesses

*            total guesses made

@param bestGame

*            best attempt

*/

static void printReport(int numGames, int numGuesses, int bestGame) {

// finding average guesses per game

double avgGuessesPerGame = (double) numGuesses / numGames;

// displaying all stats in proper format

System.out.println(“Game statistics:”);

System.out.println(“ttotal games = ” + numGames);

System.out.println(“ttotal guesses = ” + numGuesses);

// displaying average with 1 decimal fraction precision

System.out.printf(“tguesses/game = %.1fn”, avgGuessesPerGame);

System.out.println(“tbest game = ” + bestGame);

}

public static void main(String[] args) {

// initializing variables

int numGames = 0, numGuesses = 0, bestGame = -1;

char choice = ‘y’;

// displaying intro message

intro();

// looping as long as choice is y

while (choice == ‘y’) {

// playing one game

int guesses = oneGame();

// incrementing number of games played

numGames++;

// adding guesses to total

numGuesses += guesses;

// checking if user broken the best game record

if (bestGame == -1) {

// first game, setting guesses as best game

bestGame = guesses;

else if (guesses < bestGame) {

// user broke the old record

bestGame = guesses;

}

// asking if user wants to play the game again

System.out.print(“Do you want to play again? (yes/no) “);

// getting user choice, converting to lower case and

// extracting first character

choice = scanner.next().toLowerCase().charAt(0);

}

// printing final report

printReport(numGames, numGuesses, bestGame);

}

}

/*OUTPUT*/

This program allows you to play a guessing game.

I will think of a number between 1 and 100

and will allow you to guess until you get it.

For each guess, I will tell you whether the right

answer is higher or lower than your guess.

I’m thinking of a number between 1 and 100…

Your guess: 60

It’s higher.

Your guess: 80

It’s higher.

Your guess: 90

It’s higher.

Your guess: 100

You got it right in 4 guesses!

Do you want to play again? (yes/no) yes

I’m thinking of a number between 1 and 100…

Your guess: 90

It’s lower.

Your guess: 20

It’s higher.

Your guess: 50

It’s higher.

Your guess: 70

It’s lower.

Your guess: 60

It’s lower.

Your guess: 58

It’s lower.

Your guess: 55

You got it right in 7 guesses!

Do you want to play again? (yes/no) y

I’m thinking of a number between 1 and 100…

Your guess: 50

It’s lower.

Your guess: 25

It’s higher.

Your guess: 34

It’s lower.

Your guess: 30

You got it right in 4 guesses!

Do you want to play again? (yes/no) no

Game statistics:

total games = 3

total guesses = 15

guesses/game = 5.0

best game = 4

iWriteHomework
Order NOW for a 10% Discount
Pages (550 words)
Approximate price: -

Why Us?

Top Quality and Well-Researched Papers

All ourbpapers are written from scratch. In fact, Clients who ask for paraphrasing services are highly discouraged. We have writers ready to craft any paper from scratch and deliver quality ahead of time.

Professional and Experienced Academic Writers

Our writers keeps you posted on your papers progress - providing you with paper outline/draft. You are also at liberty to communicate directly with your writer.

Free Unlimited Revisions

If you think we missed something, send your order for a free revision. You have 10 days to submit the order for review after you have received the final document. You can do this yourself after logging into your personal account or by contacting our support.

Prompt Delivery and 100% Money-Back-Guarantee

All papers are always delivered on time, in many cases quite ahead of time. In case we need more time to master your paper, we may contact you regarding the deadline extension. In case you cannot provide us with more time, a 100% refund is guaranteed.

Original & Confidential

We use several writing tools checks to ensure that all documents you receive are free from plagiarism. Our editors carefully review all quotations in the text. We also promise maximum confidentiality in all of our services.

24/7 Customer Support

Our support agents are available 24 hours a day 7 days a week and committed to providing you with the best customer experience. Get in touch whenever you need any assistance.

Try it now!

Calculate the price of your order

Total price:
$0.00

How it works?

Follow these simple steps to get your paper done

Place your order

Fill in the order form and provide all details of your assignment.

Proceed with the payment

Choose the payment system that suits you most.

Receive the final file

Once your paper is ready, we will email it to you.

Our Services

No need to work on your paper at night. Sleep tight, we will cover your back. We offer all kinds of writing services.

Essays

Essay Writing Service

No matter what kind of academic paper you need and how urgent you need it, you are welcome to choose your academic level and the type of your paper at an affordable price. We take care of all your paper needs and give a 24/7 customer care support system.

Admissions

Admission Essays & Business Writing Help

An admission essay is an essay or other written statement by a candidate, often a potential student enrolling in a college, university, or graduate school. You can be rest assurred that through our service we will write the best admission essay for you.

Reviews

Editing Support

Our academic writers and editors make the necessary changes to your paper so that it is polished. We also format your document by correctly quoting the sources and creating reference lists in the formats APA, Harvard, MLA, Chicago / Turabian.

Reviews

Revision Support

If you think your paper could be improved, you can request a review. In this case, your paper will be checked by the writer or assigned to an editor. You can use this option as many times as you see fit. This is free because we want you to be completely satisfied with the service offered.

× Contact Live Agents