I am trying to develop a simple high low game that asks the user after playing if they would like to play again. If I remove the outer while loop the logic of the inner loop does exactly what I want it to do, however I am unsure how to wrap the inner loop with an outer loop that will ask the play again question and if the answer is yes put them back into the inner loop. Below is my code.
import java.util.Scanner;
import java.util.Random;
public class HiLoGuess {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100)+1; // Generates a random number for the game.
int count = 0; // Placeholder for the guess counter.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
String newgame = "y";
while (newgame.equalsIgnoreCase("y"))
{
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{
System.out.println ("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0 )
{
System.out.println("Your guess is too low, guess again");
}
else if (guess > answer)
{
System.out.println ("Your guess is to high, guess again");
}
else if (guess == answer)
{
System.out.println ();
System.out.println ("You guessed correctly, you win!!!");
System.out.println ("It took you " + count + " guesses");
}
}
System.out.print();
System.out.println("Play another game: y or n?");
newgame = scan.nextLine();
}
}
}
You need to put these initializations into the outer loop:
int guess = -1;
int answer = numb.nextInt(100)+1;
int count = 0;
Otherwise they keep the value from the last game and the inner loop will not be executed any more.
you never reset your guess, sentinel, or answer variables
so (guess != sentinel && guess != answer) always evaluates to false after the first time the game is played, and therefore the inner while loop never executes after the first game
while (guess != sentinel && guess != answer) //this is false after the first game because you don't reset variables
{ ...}
Update for OP comment:
to get your code to do what you want you need to add the resets between the outter and inner while loop like this
while (newgame.equalsIgnoreCase("y"))
{
guess = -1;
answer = numb.nextInt(100)+1;
count = 0;
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{ ...}
}
Replace newgame = scan.nextLine(); by this : newgame = scan.next();
And you need to initialise your variables inside your while loop, so that the flag is reseted to false and the random generate new result to guess.
public class Game
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
String newgame = "y";
while (newgame.equalsIgnoreCase("y")) {
int count = 0; // Placeholder for the guess counter.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100) + 1; // Generates a random number for the game.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
while (guess != sentinel && guess != answer) // Loop that ends when user enters a zero.
{
System.out.println("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0) {
System.out.println("Your guess is too low, guess again");
} else if (guess > answer) {
System.out.println("Your guess is to high, guess again");
}
else if (guess == answer) {
System.out.println();
System.out.println("You guessed correctly, you win!!!");
System.out.println("It took you " + count + " guesses");
}
}
System.out.println();
System.out.println("Play another game: y or n?");
newgame = scan.next();
}
}
}
Related
import java.util.Scanner;
import java.util.Random;
/*
* 1) the user can attempt many times and you need to display the number of successful attempt
* 2) the range of random number 1..49
* 3) output >> You successfully guess the number in 16 attempts
* 4) output >> Do you want to play again?
* */
public class GuessingGame {
public static void main(String[] args) {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count=0;
String in;
char again;
System.out.println("Welcome to Guessing Game");
do {
number = randNum.nextInt(50); // random number in the range of 1..50
for(int i=0; i<5; i++)
{
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
if(guessNumber > number)
{
System.out.println("Too big");
}else if(guessNumber < number)
{
System.out.println("Too small");
}else
{
System.out.println("Success");
count+=1;
return;
}
}
System.out.println("You successfully guess the number in "+count);
System.out.println("Do you want to play again? ");
in = uInput.nextLine();
again = in.charAt(0); //again will hold the first character from in var
}while(again =='Y'|| again =='y');
System.out.println("Guessing game terminate, thank you");
}
}
public static void main(String[] args) {
System.out.println("Welcome to Guessing Game");
guessNumber();
System.out.println("Guessing game terminate, thank you");
}
private static void guessNumber() {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count = 0;
String in;
char again;
boolean isCorrect = false;
number = randNum.nextInt(50); // random number in the range of 1..50
while (!isCorrect) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
count += 1;
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
isCorrect = true;
}
}
System.out.println("You successfully guess the number in " + count + " attempts");
System.out.println("Do you want to play again? yes/no");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
if (again == 'Y' || again == 'y') {
guessNumber();
}
}
All you have to do is to replace your do while loop with a while loop. But the point is that you must set an initial value 'Y' to your again char to start the while loop. the condition of the loop will be just the same. The code will be like : char again = 'Y';
while (again == 'Y' || again == 'y') {
System.out.println("Welcome to Guessing Game");
number = randNum.nextInt(50);
for (int i = 0; i < 5; i++) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt();
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
count += 1;
break;
}
}
System.out.println("You have successfully guessed the number for " + count + " times");
System.out.println("Do you want to play again? ");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
}
System.out.println("Guessing game terminate, thank you");
I must note that your count variable, contains the number of games which user has guessed the number successfully, and not the number of attempts during a single game. If you want to handle this too, create attempts variable inside the while loop and increase it whenever the user attempts.
Also I changed the line in = uInput.nextLine(); to in = uInput.next(); because I believe your scanner input will be skipped.
I'm creating a HiLo guessing game in Java. Everything I have so far works as intended except at the end when I prompt a user to play again, the random number remains the same from the previous game. How do I make it so the code produces a new random number when the user chooses to play a new game?
int answer = (int)(Math.random() * 100 + 1);
int guess = 0;
int guessCount = 0;
boolean playGame = true;
String restart;
Scanner scan = new Scanner(System.in);
while(playGame == true)
{
while (playGame == true)
{
System.out.println("Enter a number between 1 and 100: ");
guess = scan.nextInt();
guessCount ++;
System.out.println(answer);
if (guess < 1 || guess > 100)
{
System.out.println("You have entered an invalid number.");
guessCount --;
} else if (guess == answer)
{
System.out.println("Correct! Great guess! It took you " + guessCount + " tries!");
break;
} else if (guess > answer)
{
System.out.println("You've guessed too high! Guess again: ");
} else if (guess < answer)
{
System.out.println("You've guessed too low! Guess again: ");
}
}
System.out.println("Would you like to play again? Y/N");
restart = scan.next();
if (restart.equalsIgnoreCase("Y"))
{
playGame = true;
} else if(restart.equalsIgnoreCase("N"))
{
System.out.println("Thank you for playing!");
break;
}
}
The value in the variable 'answer' remains same since variable is a reference to what you have stored / Initialized or Assigned. It does not manipulate in itself. You have to rewrite the code for e.g. answer = (int)(Math.random()*100+1) at the point before game will be restarted or after it.
You're initializing the answer before the loop, it never changes. You have to assign answer a new value when the user chooses to play a new round. This is not the code I'd write, but here it is:
if (restart.equalsIgnoreCase("Y"))
{
answer = (int)(Math.random() * 100 + 1);
}
Design an application that picks a random number 1 through 100, and then prompt the user to guess the number, warning the user they only have 5 tries remaining to guess correctly. After each guess, report to the user whether he or she is correct or guess was too high or too low. If guesses correctly, print out congratulatory message. If guess 5 times unsuccessfully, print a message saying the game is over. At the end of the game, prompt hte user to indicate whether or not he/she wishes to play again.
I specifically need help with the ending, and I guess also the layout of the code... I run it and it continually runs, I've tried using several websites and my textbook but no luck, thank you in advance!!
Java, Net beans 8.2
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main (String[]args)
{
int answer, guess,attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101)+1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
{
guess = scan.nextInt();
while (guess != 0)
{
if(guess==answer)
System.out.println("Right!");
else if (guess<answer)
System.out.println("Your guess was too LOW.");
else if (guess>answer)
System.out.println("Your guess was too HIGH.");
}
System.out.println("Want to Play again?(y/n)");
another = scan.next();
while (guess != answer && ++attemptsNum < maxAttempts)
if (attemptsNum == maxAttempts)
System.out.println ("The number was " + answer);
}
}
}
Enter your guess (0 to quit): 20
Your guess was too LOW
Enter your guess (0 to quit): 35
Your guess was too LOW
Enter your guess (0 to quit): 80
Your guess was too HIGH
Enter your guess (0 to quit): 74
Your guess was too HIGH
Enter your guess (0 to quit): 56
Right! Guesses:5
Play again (y/n)?
Couple of comments:
You need to work on your formatting of the code. This makes it a lot more readable.
Your generator generates a value between 1 and 101. It should just be answer = generator.nextInt(100)+1;
Your loops and some of your logic is wrong
I would suggest always creating a separate method outside public static void main. This is common practice, and this also allows you to call the method it self again.
This is how i would solve it:
import java.util.Random; import java.util.Scanner;
class Main {
public static Scanner scan = new Scanner(System.in);
public static void main (String[]args) {
runGame();
}
public static void runGame() {
String another = "";
int answer, guess,attemptsNum = 0;
final int maxAttempts = 5;
Random generator = new Random();
answer = generator.nextInt(100)+1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
while (guess != answer && attemptsNum < maxAttempts-1 && guess != 0 ) {
if(guess==answer)
System.out.println("Right!");
else if (guess<answer) {
System.out.println("Your guess was too LOW.");
attemptsNum++;
guess = scan.nextInt();
}
else {
System.out.println("Your guess was too HIGH.");
attemptsNum++;
guess = scan.nextInt();
}
}
System.out.println ("The number was " + answer);
System.out.println("Want to Play again?(y/n)");
another = scan.next();
System.out.println("another = " + another);
if(another.equals("y")) {
runGame();
} else {
System.out.println("Goodbye!");
}
}
}
But either way, just continue to practice. You will get the hang of it!
I see the outer while loop needs to be restructured and some of the logic is misplaced. Try the revised version, hope this helps. Comment me if you have any questions.
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int answer, guess, attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101) + 1;
while (another.equals("y") || another.equals("Y")) {
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
attemptsNum = 0;
while (guess != 0)
{
attemptsNum++;
if (guess == answer) {
System.out.println("Right!");
break;
} else if (guess < answer)
System.out.println("Your guess was too LOW.");
else if (guess > answer)
System.out.println("Your guess was too HIGH.");
if (attemptsNum == maxAttempts) {
System.out.println("The number was " + answer);
break;
}
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
}
System.out.println("Want to Play again?(y/n)");
another = scan.next();
}
System.out.println("Thanks for playing");
}
}
I can see that javapedia.net has answered first, but I have come up with this answer independently. I have added brackets for readability. attemptsNum++ is added to the if statements for a guess being too high or low.
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int answer, guess, attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101) + 1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
while (guess != 0) {
if (guess == answer) {
System.out.println("Right!");
guess = 0;
} else if (guess < answer) {
System.out.println("Your guess was too LOW.");
attemptsNum++;
guess = scan.nextInt();
} else {
System.out.println("Your guess was too HIGH.");
attemptsNum++;
guess = scan.nextInt();
}
if (attemptsNum >= (maxAttempts-1)) {
System.out.println("The number was " + answer);
}
}
}
}
the application is a simple guessing game which i got that part down. my issue is making a method that before any guessing starts the player must first guess the right amount of digits in a number
e.g the guess being 314 and the answers has 3 digits in it then the guessing of too high two low starts otherwise it keeps looping until you guess the right amount of digits.
now i have created the method to do this my issue is a rather simple one i think but its a matter of initializing the variables and that's where i am having problems.
import java.util.Random;
import java.util.Scanner;
public class NumberGuess
{
public static void main (String[] args)
{
final int MAX = 1000;
int answer, guess;
Scanner Keyboard = new Scanner(System.in);
Random generator = new Random(); //Random generator. 1 to 100.
answer = generator.nextInt(MAX) +1;
guess = Keyboard.nextInt();
System.out.print ("I'm thinking of a number between 1 and "+ MAX + ". Guess what it is: (or enter 0 to quit) ");
do
{
System.out.print("Guess what the number is: ");
guess = Keyboard.nextInt();
if (guess > answer && guess != 0)
System.out.println("Your guess is too high!");
else if (guess < answer && guess !=0)
System.out.println("Your guess is too low!");
if(guess==0)
System.out.println("you have ended your game");
else if (guess == answer)
System.out.println("You got it!");
} while (guess != answer&& guess!=0);
}
int NumOfDigits(int number)
{
int numDigits = 0;
while (number/10 > 0);
{
number = number/10;
numDigits++;
}
return numDigits;
}
int guess;
Scanner Keyboard1 = new Scanner(System.in);
guess = Keyboard1.nextInt();
int target = NumOfDigits(answer);
while(NumOfDigits(guess) != target);
{
System.out.println("read anothrer input guess");
guess = Keyboard1.nextInt();
}
System.out.println("you got the correct number of digits now guess the number!");
guess = Keyboard1.nextInt();
}
your method for counting diigits is wrong it should be like this
public static int NumOfDigits(int number)
{
int numofdigits = 0;
while(number>0){
numofdigits++;
number = number/10;
}
return numofdigits;
}
because your method returns 2 and it should return 3
In the following code The first method (generateRandomNumber) generates a random no between 1 and 10. The second method (guessRandomNumber) then allows the user to guess the number. The problem I am having is that when the user guesses the number wrong it generates another random number instead of the inital one. As a result the user could guess and never get it correct even by entering every possible number. Can anyone advise how I would change this.
First method (generating the number):
public static int generateRandomNumber() {
Random random = new Random();
// Declaring int for random number and defaulting to 0
int randomNumber = 0;
// Assigning randomNumber between 1 and 10
randomNumber = random.nextInt(10);
randomNumber++;
return randomNumber;
}// end of generateRandomNumber
Second Method (guessing the number):
public static void guessRandomNumber() {
// declare var for user guess and default to zero
int userGuess = 0;
boolean validNumber=false;
boolean correctGuess=false;
do{
do{
try{
validNumber=true;
// Get user guess (between 1 and 10)
System.out.println("Please enter a number between 1 and 10...");
userGuess = scanner.nextInt();
}catch (Exception ex){
System.out.println("Sorry invalid entry...");
//Flush scanner
scanner.next();
validNumber=false;
}
}while (!validNumber);
if (userGuess == generateRandomNumber()) {
System.out.println("Guess correct, well done!");
correctGuess=true;
} else {
System.out.println("Sorry guess Incorrect please try again!");
correctGuess=false;
}
}while (!correctGuess);
}// end ofGuessRandomNumber
Attempt:
public static void guessRandomNumber() {
// declare var for user guess and default to zero
int userGuess = 0;
boolean validNumber=false;
boolean correctGuess=false;
int secretNumber=generateRandomNumber();
do{
do{
try{
validNumber=true;
// Get user guess (between 1 and 10)
System.out.println("Please enter a number between 1 and 10...");
userGuess = scanner.nextInt();
}catch (Exception ex){
System.out.println("Sorry invalid entry...");
//Flush scanner
scanner.next();
validNumber=false;
}
}while (!validNumber);
if (userGuess == secretNumber) {
System.out.println("Guess correct, well done!");
correctGuess=true;
} else {
System.out.println("Sorry guess Incorrect please try again!");
correctGuess=false;
}
}while (!correctGuess);
}// end ofGuessRandomNumber
You need to generate the random number first, before the user guesses, and store it in a variable. Then, instead of calling generateRandomNumber() in the line
if (userGuess == generateRandomNumber())
you need to compare it with that variable.
You should generate the random number before the first do loop. Keep it in a variable called correctNumber, then test that userGuess == correctNumber.