Restart program/game - java

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")){
}
//}

Related

Java guessing letter game

Hi im currently creating a guessing letter game! So far i have made it so you guess between the numbers 1 and 26 using the java.util.random class. However this random number should be converted into the corresponding number within the alphabet! ie a=1 etc..This is where my problem is i dont know how to convert this randomly generated number into a letter! This needs to be related to the integer as i have to able to tell the user if they are above the letter in the alphabet or to low based on the guess they entered! One more thing is that the users guess will be a letter also! Below is my code! Any help will be greatly appreciated!
{
Random rand = new Random(); //This is were the computer selects the Target
int guess;
int numGuesses = 0;
int Target;
String userName;
String playagain;
boolean play = true;
int session = 0;
int sessions = 0;
int bestScore = 0;
Scanner consoleIn = new Scanner(System.in);
Scanner name = new Scanner(System.in);
System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
userName= name.nextLine();
System.out.println("Hello "+ userName + " :) Welcome to the game!\n");
while (play = true)
{
session++;
Target = rand.nextInt(26) + 1;
System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have
do {
guess = consoleIn.nextInt();
numGuesses++;
if (guess > 26)
System.out.println("Error! Above MAXIMUM range");
else if (guess <= 0)
System.out.println("Error! Below MINIMUM range");
else if (guess > Target)
System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
else if (guess < Target)
System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
}
while(guess != Target && numGuesses <5);
if(guess == Target) {
System.out.println("Congratulations "+ userName + ", it took you "+ numGuesses +" attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
sessions++;
}
else
{
System.out.println("Sorry "+ userName + ", You've used up all of your guesses! The correct answer was "+ Target + "!"); //This tells the player that they failed to find the number and then tells them what the correct answer
}
{
Scanner answer = new Scanner(System.in);
System.out.println("Would you like another GO "+ userName +"? [Y/N]");//This asks the player if they would like to play again
playagain = answer.nextLine();
if(playagain.equalsIgnoreCase("Y"))//This is what happens if the player opts to play again
{
play = true;
numGuesses = 0;
} else if(playagain.equalsIgnoreCase("N"))//This is what happens if the player opts to exit the game
{
play = false;
System.out.println("Thanks for playing "+ userName +"! :) Please come back soon!");
System.out.println("You had "+ session +" Goes");
System.out.println("The number of times you guessed correctly: "+ sessions +"");
break;
}
}
}
}
Random random = new Random();
char c = (char) (random.nextInt(26) + 'a');
This maps (0 to 25 ) to ('a' to 'z')

Ending and restarting a program from user input

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;}
}
}
}

Having issues with having a program re-run

I am writing a program that will ask the user to guess a random number 6 times. The program has to ask if they want to play again and will keep a running total of the wins/losses.
How would I have the program rerun?
heres the code:
import java.util.Scanner;
import java.util.Random;
public class Project {
public static void main(String[] args) {
String input;
double guess = 0;
int number;
double wins = 0;
double losses = 0;
String repeat;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to Higher/Lower!");
System.out.println("Enter your name: ");
input = keyboard.nextLine();
while(input.equalsIgnoreCase("yes")); {
number = randomNumbers.nextInt(100) + 1;
System.out.println("I've chosen my number, " + input + "You only have 6 tries, good luck!"); }
for(int num = 1; number != guess && number <= 6; num++) {
System.out.println("Enter guess " + num + ":");
guess = keyboard.nextDouble();
if(guess < number)
System.out.println("higher.");
else if(guess > number)
System.out.println("lower.");
else
System.out.println("Congratulations!"); }
if(guess == number) {
System.out.println("You guesses my number!"); wins++; }
if(guess != number) {
System.out.println("Sorry, " + input + " my number was " + number +
"You lose!"); losses++; }
System.out.println("Do you want to play again? (Yes/No): ");
repeat = keyboard.nextLine();
if(input.equalsIgnoreCase("no")); {
System.out.println("Thanks for playing!"); }
System.out.println(wins + " wins");
System.out.println(losses + " losses");
}
}
It is skipping over asking me if i want to play again or not and i dont know what kind of loop to use
Wihtout your code, I'm assuming this is what you need.
boolean doContinue = true;
do {
//guess random number 6 times
//do you want to continue?
// yes -> doContinue = true;
// no -> doContinue = false;
} while (doContinue );
I would suggest making your loop a do-while loop like this:
do {
for (int i=0; i<6; i++){
/*
insert code for the guessing/checking/etc.
*/
}
System.out.print("Would you like to continue? [Y/n] ");
} while (scan.next().toUpperCase().charAt(0) != 'Y');

Play Again feature not working

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;
...
}

Stuck in a loop when attempting to evaulate a number repeatedly

My Goal: To make a program that can check if the number you guessed is correct. It will tell you if it's too high/low. It needs to continue giving you chances until you guess correctly. Also, it needs to be able to resume from the start after you finish if you want to.
Problem: My if statements are stuck in an infinite loop, and attempting to restart the program at the end does not work at all.
import java.util.Random;
import java.util.Scanner;
public class driver {
public static void main (String [] args) {
// Output number of guesses.
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100) + 1;
System.out.println(randomInt);
System.out.println("Welcome to my guessing game. What is your first guess that is between 1 and 100?");
int userInput = scan.nextInt();
String playAgain = "Y";
int guesses = 0;
System.out.println(randomInt);
while (playAgain == "Y") {
if (userInput > 0 && userInput < 100) {
if (userInput == randomInt){
guesses++;
System.out.println ("Right! Guesses: " + guesses);
playAgain = "f";
}
// Too low
else if (userInput < randomInt) {
guesses++;
System.out.println ("Your guess was too LOW.");
}
// Too high
else {
System.out.println ("Your guess was too HIGH.");
guesses++;
}
}
}
// I want to be able to resume from the top if the user says Y.
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
}
The last two lines should be inside your while loop, the problem is with your braces
while (playAgain == "Y") {
if (userInput > 0 && userInput < 100) {
if (userInput == randomInt){
guesses++;
System.out.println ("Right! Guesses: " + guesses);
playAgain = "f";
}
else if (userInput < randomInt) {
guesses++;
System.out.println ("Your guess was too LOW.");
}
else {
System.out.println ("Your guess was too HIGH.");
guesses++;
}
}
}
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
The bottom part should look like:
guesses++;
}
}
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
}
The way it was means that the condition of your while is never updated. I assume you want it to update after each input from the user.

Categories

Resources