HiLo Game With Random Number Generator - java

i have one real quick question about this HiLo game. When I go and test it everything works properly except when I want it to display how many tries it took them to guess. What I'm trying to say is it doesn't count the initial guess, but counts the ones after it so it shows one less guess than what it actually is. Here is my code.
EDIT:I have another quick question. I want the program not to count the guess if it is out of range from 0 to 10. How would i go about doing so because when I run the program it counts the guess as one of my tries.
import java.util.Random; // Random number generator class
import java.util.Scanner; // reads user inputs
public class HiLo
{
public static void main (String[] args)
{
//declare variables
final int MAX = 10;
int answer, guess;
int numberOfTries = 0 ;
String again;
Scanner Keyboard = new Scanner(System.in);
do
{
System.out.print (" I'm thinking of a number between 0 and "
+ MAX + ". Guess what it is: ");
guess = Keyboard.nextInt();
//guess
Random generator = new Random(); //Random number generator. 0 to 10.
answer = generator.nextInt(MAX) +1;
if (guess > 10)//if guess is bigger than 10 then error message
{
System.out.println ("ERROR – Your guess is out of the range 0 to 10.");
}
if (guess < 0)//if guess is smaller than 0 then error message
{
System.out.println ("ERROR – Your guess is out of the range 0 to 10.");
}
while (guess != answer )//If guess is not the answer
{
if (guess > answer )//If guess is more than the answer
{
System.out.println ("You guessed too high! \nTry again:");
guess = Keyboard.nextInt();
}
if (guess < answer )//If guess is less than the answer
{
System.out.println ("Too Low! \nTry again:");
guess = Keyboard.nextInt();
}
numberOfTries=numberOfTries+1;
}//end of the loop
// display result
if ( guess == answer)
{
numberOfTries += 1;
System.out.println ("YOU WIN!");
System.out.println("It took you " + numberOfTries + " tries!") ;
System.out.println();
System.out.print( "Do you want to play again(Y/N)?");
}
Keyboard.nextLine(); // skip over enter key
again = Keyboard.nextLine();
numberOfTries=0;
}while (again.equalsIgnoreCase ("Y") );
} // end of class
} //end of main
Thank you!

You should put numberOfTries += 1 inside if ( guess == answer ), this way it counts the correct answer as well
if ( guess == answer)
{
numberOfTries += 1; // <--- This adds the final guess
System.out.println ("YOU WIN!");
System.out.println("It took you " + numberOfTries + " tries!") ;
System.out.println();
System.out.print( "Do you want to play again(Y/N)?");
}

You should set numberOfTries to 1 when you initialise it and reset it, that way it already takes into account the first guess before entering the while (guess != answer ) loop

Related

Issue with Java Guessing Game

I'm working on this guessing game for school. I've realized that at some point I deleted my while loop for the user's guess equalling the computer's random number and it has messed up the results of my program. I thought that I could just add a nested while loop, but that hasn't worked. I've been trying to figure this out for hours.
Any ideas how to add something like while (guess == number) to my code and keep it working?
/*
Programming Assignment #3: Guess
Peter Harmazinski
Week 8
Guessing Game
*/
import java.util.*;
public class Guess {
public static final int RANGE = 100;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
boolean again = true;
double guessesDividedByGames = 0;
int maxGuesses = 0;
int numGames = 0;
int numGuesses = 1;
int totalGuesses = 0;
Random rand = new Random();
int number = rand.nextInt(RANGE) + 1;
int guessTracker = 0;
while(again) {
getInstructions();
int guess = getGuess(console);
numGuesses = getHigherLower(guess, number, console);
totalGuesses += numGuesses;
again = playAgain(numGuesses, console);
numGames++;
if (numGuesses > maxGuesses) {
maxGuesses = numGuesses;
}
}
guessesDividedByGames = (double)totalGuesses / numGames;
getResults(numGames, totalGuesses, guessesDividedByGames, maxGuesses);
}
//Prints instructions for user
public static void getInstructions() {
System.out.println("This program allows you to play a guessing game");
System.out.println("I will think of a number between 1 and " + RANGE);
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");
System.out.println("right answer is higher or lower than your guess");
System.out.println("");
}
//Allows the user to play again if first letter of input is "y" or "Y"
public static boolean playAgain(int guessesNum, Scanner console) {
boolean anotherTime = false;
System.out.println("You got it right in " + guessesNum + " guesses.");
System.out.println("");
System.out.print("Do you want to play again? ");
String repeat = console.next();
String[] yesOrNo = repeat.split("");
System.out.println("");
if (yesOrNo[0].equals("y") || yesOrNo[0].equals("Y")) {
anotherTime = true;
}
return anotherTime;
}
//Outputs the results if the user doesn't play again
public static void getResults(int gamesTotal, int guessesTotal, double guessesDividedByGames, int guessesMax) {
System.out.println("Overall results:");
System.out.println("\ttotal games\t= " + gamesTotal);
System.out.println("\ttotal guesses\t= " + guessesTotal);
System.out.println("\tguesses/game\t= " + guessesDividedByGames);
System.out.println("\tmax guesses\t= " + guessesMax);
}
//Tells the user whether the random number is higher or lower
//and then returns the number of guesses
public static int getHigherLower(int guess, int randomNumber, Scanner console) {
int guessIncreaser = 1;
while (guess > randomNumber) {
System.out.println("lower");
guess = getGuess(console);
guessIncreaser++;
}
while (guess < randomNumber) {
System.out.println("higher");
guess = getGuess(console);
guessIncreaser++;
}
return guessIncreaser;
}
//Asks the user to guess the random number
//then returns the guess
public static int getGuess(Scanner console) {
System.out.println("I'm thinking of a number...");
System.out.print("Your Guess? ");
int playerGuess = console.nextInt();
while (playerGuess < 1 || playerGuess > RANGE) {
System.out.println("Out of range, please try again.");
System.out.print("Your Guess? ");
playerGuess = console.nextInt();
}
return playerGuess;
}
}
The problem appears to be your getHigherLower method, specifically these two while blocks:
while (guess > randomNumber) {
System.out.println("lower");
guess = getGuess(console);
guessIncreaser++;
}
while (guess < randomNumber) {
System.out.println("higher");
guess = getGuess(console);
guessIncreaser++;
}
If the user guessed a number lower than randomNumber, then higher, both while blocks would be escaped. Instead, what you want is this:
while (guess != randomNumber) {
if (guess > randomNumber) {
System.out.println("lower");
}
else {
System.out.println("higher");
}
guess = getGuess(console);
guessIncreaser++;
}
What you need is one big while loop not two little ones
while (guess != randomNumber) {
if (guess > randomNumber) {
System.out.println("lower");
} else {
System.out.println("higher");
}
guess = getGuess(console);
guessIncreaser++;
}
First off, I'm hesitant to just give you the answer in code since this is for a school project and we learn by challenging ourselves and actualizing solutions. But I'm willing to point you in the right direction.
1. getHigherLower()
As others have pointed out, your two while loops are set up to cause errors. For instance, if I first guess too low, and then too high, your method mistakenly tells me I guessed correctly. This is a big problem!
Random number = 63
Guess 1 = 34 (lower)
Guess 2 = 100 (higher)
Actually your program tells me my guess of "100" when the number is "63" is correct!
// 1st conditional check: 34 !> 63, so skips first while loop
while (guess > randomNumber) {
guess = getGuess(console);
}
// 1st conditional check: 34 < 63, so enters second while loop
// 2nd conditional check: 100 !< 63, so skips second while loop
while (guess < randomNumber) {
// guess now becomes 100, goes back to top of while loop to check condition again
guess = getGuess(console);
}
// returns and exits method here (program wrongly thinks user has guessed correctly!)
Note that you can do a
System.out.println("random number: " + number);
to test that you're actually guessing the random number correctly. You might look into some JUnit testing as well.
James Ko seems to have a good feel for a better method implementation.
2. playAgain()
You use an if statement to check if the first index in an array of strings equals "y" or "Y" but your program never continues. Why is this?
if (yesOrNo[?].equals("y") {
anotherTime = true;
}
You should consider whether user input is really being placed at the first index or not?
Hint: loop through the "yesOrNo" array and print out each index to see where the user input is being placed in the array.
for (int i = 0; i < yesOrNo.length; i++) {
System.out.println("String at index " + i + ": " + yesOrNo[i]);
}
Good luck and remember that testing is your friend!

Why does my HiLo game allow guesses outside of the 0-10 range?

I have a quick question about this HiLo game that I have been trying to fix from a while now. When I run the program it counts guesses outside of the 0-10 range, but I don't want it to do that. How do I fix that? Here is my code.
import java.util.Random; // Random number generator class
import java.util.Scanner; // reads user inputs
public class HiLo
{
public static void main(String[] args)
{
// declare variables
final int MAX = 10;
int answer, guess;
int numberOfTries = 0;
String again;
Scanner Keyboard = new Scanner(System.in);
do
{
System.out.print(" I'm thinking of a number between 0 and "
+ MAX + ". Guess what it is: ");
guess = Keyboard.nextInt();
// guess
Random generator = new Random(); // Random number generator. 0 to 10.
answer = generator.nextInt(MAX) + 1;
if (guess > 10) // if guess is bigger than 10 then error message
{
System.out.println("ERROR – Your guess is out of the range 0 to 10.");
}
if (guess < 0) // if guess is smaller than 0 then error message
{
System.out.println("ERROR – Your guess is out of the range 0 to 10.");
}
while (guess != answer) // If guess is not the answer
{
if (guess > answer) // If guess is more than the answer
{
System.out.println("You guessed too high! \nTry again:");
guess = Keyboard.nextInt();
}
if (guess < answer)// If guess is less than the answer
{
System.out.println("Too Low! \nTry again:");
guess = Keyboard.nextInt();
}
numberOfTries = numberOfTries + 1;
}// end of the loop
// display result
if (guess == answer)
{
numberOfTries += 1;
System.out.println("YOU WIN!");
System.out.println("It took you " + numberOfTries + " tries!");
System.out.println();
System.out.print("Do you want to play again(Y/N)?");
}
Keyboard.nextLine(); // skip over enter key
again = Keyboard.nextLine();
numberOfTries = 0;
} while (again.equalsIgnoreCase("Y"));
} // end of class
} // end of main
You report the error but you don't continue; (and use a logical ||) like this
if (guess < 0 || guess > 10) {
System.out.println ("ERROR – Your guess is out of the range 0 to 10.");
again = "Y"; // <-- make sure we'll re-evaluate.
continue; // <-- Add then skip the rest of the loop body
}

How would I add "You got it right in ... guesses!"

I need to add "You got it right in ... guesses!" but I'm not exactly sure how. Can someone please explain to me how to do this in java?
I would like it to display a println at the end saying how many tries it took for the user to get the number correct.
import java.util.*;
public class prog210c
{
public static void main()
{
Scanner sc = new Scanner(System.in);
Random rn = new Random();
int randomNum = rn.nextInt(90) + 10;
System.out.println("I am thinking of a number between 1 and 100");
while (true) {
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
if(guess < randomNum)
{
System.out.println("Higher--Try Again");
}
else if(guess > randomNum)
{
System.out.println("Lower--Try Again");
}
else if(guess == randomNum)
{
System.out.println("Correct!");
break;
}
else
{
System.out.println("Enter a number between 1 and 100");
}
}
//System.out.println("You got it right in " + + " guesses");
} //end main
} //end class
Just create some int variable to store your number of attempts in and increment it every time you read in a guess.
int attempts = 0;
System.out.println("I am thinking of a number between 1 and 100");
while (true) {
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
attempts++;
/**
* The rest of your loop code here.
*/
}
System.out.println("You got it right in " + attempts + " guesses");
The simplest way to do this is declared a counter integer, and in your logic increment it every time the user attempts.
int guessCounter = 0;
while(true) // Also do not use an infinite while loop, have an expression that can be terminated
{
...obtain input
if(guess < randomNum)
{
...
guessCounter++;
}
else if (guess > randomNum){
....
guessCounter++;
}
System.Out.println("The number of attempts " + guessCounter);
}
You could do this by creating a variable to store the number of tries, like an int, and then add one to the int every time the user guesses, by using variable++:
public static void main(){
Scanner sc = new Scanner(System.in);
Random rn = new Random();
int tries = 0;
int randomNum = rn.nextInt(90) + 10;
System.out.println("I am thinking of a number between 1 and 100");
while(true){
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
//Rest of your code here
}
System.out.println("You got it right in " + tries + " guesses");
}
and if you want to go even above and beyond, you could make it so it says You got it right in 1 guess instead of it saying You got it right in 1 guesses, if the user gets the number correct on their first try. We can do this by using the ternary Java operator, which is pretty much a compact if-statement:
String s = (tries == 1 ? "guess" : "guesses");
What this is pretty much doing is: if this is true ? do this : else do this
Now we can change the You got it right in... part of your program to say guess instead of guesses if the user guesses the number on their first try:
String s = (tries == 1 ? "guess" : "guesses");
System.out.println("You got it right in " + tries + "" + s);

While loop bugs

Hello I am a beginner Java programmer. My Program keeps ending when I put the correct number in (with out printing the message ), or it wont go from a lower number to a higher one with out ending?
Can someone tell me what I am doing wrong?
package week3;
import java.util.Scanner;
public class Week3 {
public static void main(String[] args) {
Scanner In = new Scanner(System.in);
int Guess ;
int count = 0;
count++;
int c = 55;
System.out.println("Welcome to the Higher / Lower game! Try to guess the"
+ "number between 1 and 100. ");
System.out.print("Enter your guess: ");
Guess = In.nextInt();
if(Guess == c)
{
System.out.println("The number was 55 you guessed correctly! "
+ " it took you " + count +" tries");
}//end if
while (Guess < 1)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
Guess = In.nextInt();
}//End while < 1
while (Guess > 100)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
Guess = In.nextInt();
}//end while <100
while (Guess >= 56)
{
System.out.println("The number is lower.");
Guess = In.nextInt();
} //end while over 55
while (Guess <= 54)
{
System.out.println("The number is higher.");
Guess = In.nextInt();
}//end while lower than 55
}//end main
}//end class
I can see the problem, but you would be better off trying to find it yourself. (Or having another go ...)
Hints:
Try hand-executing the code. Pretend you are the computer, and use a pencil and paper to simulate what it would do.
Have you tried using a debugger?
Some of the comments are good hints too.
While I have your ear, you also should pay attention to your programming style. And one universal style rule for Java is that variables should start with a lower-case letter. Your In and Guess variables violate this.
System.out.println("Welcome to the Higher / Lower game! Try to guess the"
+ "number between 1 and 100. ");
while (true) {
System.out.print("Enter your guess: ");
Guess = Integer.parseint(In.nextLine());
if(Guess == c)
{
System.out.println("The number was 55 you guessed correctly! "
+ " it took you " + count +" tries");
break;
}
if (Guess < 1)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
}
if (Guess > 100)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
}
if (Guess >= 56)
{
System.out.println("The number is lower.");
}
if (Guess <= 54)
{
System.out.println("The number is higher.");
}
}
}
}
Hopefully this gives you the idea of using the while loop.
The structure of your program is incorrect.
You only need one while loop. Begin your program with a while loop, and continue with conditions, such that:
boolean numFound = false;
while (!numFound) {
//conditions
}

How do I Count the number of user inputs in this java code?

So far I have,
package randomnumberguessinggame;
import java.util.Scanner;
public class RandomNumberGuessingGame {
public static void main(String[] args) {
int secretNumber;
secretNumber = (int) (Math.random() * 999 + 1);
Scanner keyboard = new Scanner(System.in);
int guess;
int count = 0;
do {
System.out.print("Enter a guess: (1-1000) ");
guess = keyboard.nextInt();
System.out.println("Your guess is " + guess);
if (guess == secretNumber)
System.out.println("Your guess is correct. Congratulations!");
else if (guess < secretNumber)
System.out.println("Your guess is smaller than the secret number.");
else if (guess > secretNumber)
System.out.println("Your guess is greater than the secret number.");
} while (guess != secretNumber);
}
}
This code works but I need to know how to count the number of user inputs.
Thanks in advance.
Just add count++ under guess = keyboard.nextInt();
Just add one incrementation into your do while loop count = count + 1; as the last command. It would work anywhere in the do loop, but it's logical to put it after the input was processed.
Then add a line System.out.println("Number of guesses:"+count); under your loop.

Categories

Resources