I am having a few issues,
I am having issues getting my program to actually end.
I can't figure out when I prompt the user to play again how to initiate a new game.
Any guidance would be appreciated.
Thanks
import java.util.*;
public class HiLowGuessingGame {
public static void main(String[] args) {
// Creates a random number generator
Random random= new Random();
// For getting input from the user
Scanner sc = new Scanner(System.in);
int number = random.nextInt(100);
int guess = +1;
//Counts the number of guesses
int guesscount = 0;
guesscount ++;
//Allows user to quit the game
String input;
int quit = 0;
String playagain;
String y="y";
String n="n";
// Prompts user for their next guess
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
// Loop until the user guesses correctly
while (true){
// Reads the next guess
guess = sc.nextInt();
//If guess it to low or high
if (guess == quit){
System.out.println("Game Over!");}
else if (guess < number ){
System.out.println("Guess is too low, please try again");
guesscount ++; }
else if(guess > number ){
System.out.println("Guess is too high, please try again");
guesscount ++; }
// Correct guess and number of guesses
else {
System.out.println("Your guess is correct = " + number + "\n" +"Number of Guesses = " +guesscount );
while (true) {
// Play again?
boolean isplayagain = true;
while (true) {
System.out.println("play another game?(y/n)");
String playagainResponse = sc.next();
if (playagainResponse.equalsIgnoreCase("y")) {
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
guess = sc.nextInt();
break;
} else if (playagainResponse.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
isplayagain = false;
break;
}
}
if (!isplayagain) {
break;
}
}
}
}
}
}
I ran your code, and I noticed that you use break statements to exit out of the for loops, but you never break out of the outermost for loop, so the game never actually ends.
In this case however, I would recommend not using break and use System.exit(0), which will end the game normally. I'll add a reference link at the bottom. This should fix your issue of the game not ending.
As for your other problem, I'm not sure what you mean. Do you mean that it doesn't restart a new game properly? The random number is only issued at the start of the program, so when a new game is started, the random number stays the same. Also, the guess count isn't reset with a new game. I would just put all the code which resets the variables in the if-statement responsible for starting a new game.
Good luck!
https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#exit(int)
I changed your program a bit to do what you want.
If i get what you are trying to do i think this is the code for this.
import java.util.*;
public class HiLowGuessingGame {
public static void main(String[] args) {
// Creates a random number generator
Random random= new Random();
// For getting input from the user
Scanner sc = new Scanner(System.in);
int number = random.nextInt(100);
int guess = +1;
//Counts the number of guesses
int guesscount = 0;
guesscount ++;
//Allows user to quit the game
String input;
int quit = 0;
String playagain;
String y="y";
String n="n";
boolean isplayagain = false;
// Prompts user for their next guess
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
// Loop until the user guesses correctly
while (true){
// Reads the next guess
guess = sc.nextInt();
//If guess it to low or high
if (guess == quit){
System.out.println("Game Over!");
break;}
else if (guess < number ){
System.out.println("Guess is too low, please try again");
guesscount ++; }
else if(guess > number ){
System.out.println("Guess is too high, please try again");
guesscount ++; }
// Correct guess and number of guesses
else {
System.out.println("Your guess is correct = " + number + "\n" +"Number of Guesses = " +guesscount );
// while (true) {
// Play again?
while (true) {
System.out.println("play another game?(y/n)");
String playagainResponse = sc.next();
if (playagainResponse.equalsIgnoreCase("y")) {
System.out.println("New game starts now!");
isplayagain=true;
break;
} else if (playagainResponse.equalsIgnoreCase("n")) {
System.out.println("Goodbye");
isplayagain = false;
break;
}
}
if (!isplayagain)break;//cause of the program to not end if user gives n
}
if(isplayagain){
number = random.nextInt(100);
guesscount=0;
System.out.println("Enter a guess from 1 to 100, Enter 0 to quit");
isplayagain=false;}
}
}
}
Related
When I compile, that try to enter (y) to play again my do - while is not working, it takes me out of the loop.
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
int guessNumber = 0;
do
{
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
}
Change the code as below: (You just need to update the variables inside the loop)
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = 0;
int guessNumber = 0;
do
{
// new lines to be added
theNumber = (int)(Math.random() * 100 + 1);
guessNumber = 0;
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
Here is the execution of code on Jshell:
The reason the program is not working is because the do-while loop does one iteration before it gets to the "while" part. In your case, the program successfully finishes the loop after a user correctly guesses the number. Your program breaks because after that you are requiring the user to enter 'y' to continue endlessly without letting them guess a number. If they guess a number, the program terminates.
my goal in the following code is to keep getting guesses until the user either guesses the right number, or quit. To quit, I am able to easily break out of my loops, but when I try to continue in my loops, it doesn't work right. First it requires multiple inputs, and then also entirely regenerates my number, while what I want to do is to keep getting guesses (asking user) for the SAME random number.
Below is my code:
public class Test {
public static void main(String[] args) {
int count, randNum, guess;
count = 0;
Scanner scan = new Scanner(System.in);
while (true) {
Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");
guess = scan.nextInt();
count += 1;
if (guess == randNum) {
System.out.println("Correct guess.");
System.out.println("It took " + count + " tries to guess the right number");
System.out.println("Would you like to play again? ");
System.out.println("Press any letter to play again or q to quit: ");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else{
continue;
}
}
if (guess > randNum) {
System.out.println("Your guess is bigger than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}
else if (guess < randNum) {
System.out.println("Your guess is smaller than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}
}
}
}
The code for generating the random number should be before the while statement. When you call continue, it goes back to the first line of the while block and consequently generates another random number.
Your statement declaring the int randNum is inside of the while loop, so every time the while loop repeats, the number is declared (again) and set to a value between 1 and 100.
If you want to prevent this, declare the variable and initialize it with a random value outside of the while loop.
A small side note: by initializing the variable inside of the while loop, you are limiting its scope more than you probably want to. Every time it loops through, the previous randNum you created no longer exists, and it then creates a new one. Basically, if you want it to be more permanent, initialize it outside of the loop.
Also, if you only want it to ask for a number between 1 and 100 the very first time, move it outside of the loop. This however is up to you on whether or not you want it to ask each time, or just once.
//…
public static void main(String[] args) {
int count, randNum, guess;
count = 0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");
while (true) {
/*Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");*/
guess = scan.nextInt();
count += 1;
//…
Im working on this random-number-guessing game. At the end of the game I want the user to be given the option of playing again (or letting someone else play). I've found a couple of similar threads and questions but none have been able to help me solve this little issue. Im pretty sure I can use my while-loop someway but dont know exactly how..
Very new to Java so understand if this is an easy fix..
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args){
Random rand = new Random();
int correctNumber = rand.nextInt(100);
int numberOfGuesses = 0;
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
String username = "";
System.out.println("Hello, it is time to play a guessing game.");
System.out.println("We will generate a random number between 0-99, and you will have to try to guess the number in as few attempts as possible.");
System.out.println("You can also choose to give up by pressing \"q\" on your keyboard. \n\nTo get started, press \"s\" on your keyboard.");
input.nextLine();
System.out.println("\nEnter a username: ");
username = input.nextLine();
System.out.println("\nNew username registered: " + username);
while(win == false){
System.out.println("\nGuess a number between 0-99: ");
guess = input.nextInt();
numberOfGuesses++;
if (guess == correctNumber){
win = true;
}
else if(guess < correctNumber){
System.out.println("Too low. Try again!");
}else if(guess > correctNumber){
System.out.println("Too high. Try again!");
}
}
System.out.println("\nYou guessed the correct number which was " + correctNumber + ". Congrats!");
System.out.println("\n" + username + " your number of guesses were: " + numberOfGuesses);
win = false;
}
// System.out.println("\nTo play again (let someone else try) press \"s\", to quit press \"q\".");
// input.nextLine();
// if (input.next().equalsIgnoreCase("q")){
// System.out.println("\nThanks for playing!");
// }
// }else if(input.nextLine().equalsIgnoreCase("s")){
}
//}
What you're describing is called a "game loop". Basically you'd wrap your entire game in a loop which would repeat based on some condition. In this case the condition is whether or not the user wants to play again.
In Java-ish pseudo-code, the structure would look like this:
boolean keepPlaying = true;
while (keepPlaying) {
boolean hasWon = false;
while (!hasWon) {
// play a round in the game
}
keepPlaying = promptUser("Would you like to play again?");
}
The "pseudo" part of that pseudo-code of course being that last line. Simply ask the user if they'd like to play again, and convert the response to the logical value being used by the game loop.
So the game itself is a loop of "rounds" which repeat until a win or loss has occurred. And the program is a loop of "games" which repeat until the user quits.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args){
Random rand = new Random();
int correctNumber = rand.nextInt(100);
int numberOfGuesses = 0;
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
String username = "";
String choice = "No"; //new Variable
System.out.println("Hello, it is time to play a guessing game.");
System.out.println("We will generate a random number between 0-99, and you will have to try to guess the number in as few attempts as possible.");
System.out.println("You can also choose to give up by pressing \"q\" on your keyboard. \n\nTo get started, press \"s\" on your keyboard.");
input.nextLine();
System.out.println("\nEnter a username: ");
username = input.nextLine();
System.out.println("\nNew username registered: " + username);
do{
while(win == false){
System.out.println("\nGuess a number between 0-99: ");
guess = input.nextInt();
numberOfGuesses++;
if (guess == correctNumber){
win = true;
}
else if(guess < correctNumber){
System.out.println("Too low. Try again!");
}else if(guess > correctNumber){
System.out.println("Too high. Try again!");
}
}
System.out.println("\nYou guessed the correct number which was " + correctNumber + ". Congrats!");
System.out.println("\n" + username + " your number of guesses were: " + numberOfGuesses);
win = false;
//added the next two lines
System.out.println("Do you want to play again? Type \'Yes\' to play again or \'No' to quit");
choice = input.next();
}
while(choice.equalsIgnoreCase("Yes"));
}
// System.out.println("\nTo play again (let someone else try) press
\"s\", to quit press \"q\".");
// input.nextLine();
// if (input.next().equalsIgnoreCase("q")){
// System.out.println("\nThanks for playing!");
// }
// }else if(input.nextLine().equalsIgnoreCase("s")){
}
//}
I can't seem to be able have my program ask the user if they would like to play again. The program ends when asking if they would like to continue. I added a break because before the program was continuously looping the correct answer and number of tries.
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
boolean play = true;
Scanner input = new Scanner(System.in);
Random Number = new Random();
int GuessNumber = 1+ Number.nextInt(1000);
int guess = 0;
int Tries = 0;
while(play) {
while(guess != GuessNumber) {
System.out.println("Please Enter a number between 1 and 1000:");
guess = input.nextInt();
Tries++;
if(guess == GuessNumber) {
System.out.println("You Win!");
break;
}
else if(guess < GuessNumber) {
System.out.println("Guess is too low");
}
else if(guess > GuessNumber) {
System.out.println("Guess is too high");
}
}
System.out.printf("Number was: %d",GuessNumber);
System.out.println("");
System.out.printf("Number of tries was: %d ",Tries);
System.out.println("");
System.out.println("Would you like to play again?(Yes/No)");
String playagain = input.nextLine();
if("Yes".equals(playagain))
play = true;
else
play = false;
}
}
}
A few things with your program.
As the comments have noted, you do need to flush your new-line character after using nextInt().
But, you must also set the guess value and try-count back to 0 after the user states that they would like to play again -- otherwise the program will just continue in a "You win!" loop.
I would recommend moving your variable declarations to the outer loop:
while(play) {
int guess = 0;
int guessNumber = 1 + Number.nextInt(1000);
int tries = 0;
...
}
I have created a game where the user guesses a random number that was created 0-100. If their guess is too high, the system tells them to guess higher, and the same for if their guess is lower than the actual number. However, I need to initialize each guess to an array, in the order that they inputted. I know how to initialize an array, but I need help on storing the player's guesses into the array. Here is my code, and any help/advice is appreciated!
public static void randomNumGame(){
// begin of method
Scanner numbers = new Scanner(System.in);
Random randomGenerator = new Random();
int[] guess;
guess = new int[6];
guess[0]=0;
guess[1]=0;
guess[2]=0;
guess[3]=0;
guess[4]=0;
guess[5]=0;
System.out.println("running ...");
int thisRandomInt = randomGenerator.nextInt(100);
int attempt = 0;
boolean done = false;
while(!done){
System.out.print("Guess a number from 0 to 100 : ");
int myGuess = numbers.nextInt();
attempt++;
if(myGuess == thisRandomInt && attempt <= guess.length){
done = true;
System.out.println("You won. It took " + attempt+ " times to guess my number.");
}else if (attempt >= guess.length){
System.out.println("Game Over. My number is "+thisRandomInt );
done = true;
}else if (myGuess < thisRandomInt){
System.out.println("Guess a higher number");
}else{
System.out.println("Guess a lower number");
}
}
}// end of method
if(myGuess == thisRandomInt && attempt <= guess.length){
done = true;
System.out.println("You won. It took " + attempt+ " times to guess my number.");
}else if (attempt >= guess.length){
System.out.println("Game Over. My number is "+thisRandomInt );
done = true;
}else if (myGuess < thisRandomInt){
guess[attempt-1] = myGuess;
System.out.println("Guess a higher number");
}else{
guess[attempt-1] = myGuess;
System.out.println("Guess a lower number");
}
You don't need to explicitly init your quest array with zeroes. Apart from that, you can do something like this:
System.out.print("Guess a number from 0 to 100 : ");
int myGuess = numbers.nextInt();
guess[attempt++] = myGuess;
Also, instead of the done flag, you can call break instead of declaring the flag true - it will escape the loop.