I'm making a simple guess game but I don't know how to ask the player if the want to play the game again.Everytime the game ends I have to run the game again so I want to add this feature to it.I looked in some other posts but they didn't help.Here's the code:
import java.util.*;
public class guessNumber{
private static Scanner userInput = new Scanner(System.in);
public guessNumber(){
System.out.println("~~~Guess Game~~~");
}
public void guessGame(){
System.out.println("Enter the maximum number:");
int maxNum = userInput.nextInt();
System.out.println("Guess a number between 0 and " + maxNum + ":");
int randomNumber = (int) (Math.random() * maxNum);
boolean gameOn = true;
int numberOfTries = 0;
while(gameOn){
boolean printOthers = true;
numberOfTries++;
int number = userInput.nextInt();
if(number > maxNum){
System.out.println("Please enter a number between 0 and " + maxNum + ".");
printOthers = false;
}
if(printOthers){
if(number == randomNumber){
System.out.println("=================================");
System.out.println("You guessed the right number xD.");
System.out.println("Your tried " + numberOfTries + " times.");
System.out.println("=================================");
}else if(number > randomNumber){
System.out.println("Try a lower number");
}else if(number < randomNumber){
System.out.println("Try a higher number");
}
else{
System.out.println("Please enter a number between 0 and " + maxNum + ".");
}
}
}
}
public static void main(String[] args){
guessNumber guess = new guessNumber();
guess.guessGame();
}
}
In your main use a while loop. In the loop first call your guessGame() then, similarly to how you ask to enter a number, you ask if they want to play again (Y/N ?) and if they say no you break the loop otherwise you go ahead...
Add your calling method in main method with in a while loop
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
do{
//call your game
System.out.println("Do you want to play again. Press y");
}
while(scanner.next().equals("y"));
Related
so i made a game, in which user needs to guess the random number or letter. I want to make it so that when the user writes 'end game' during the game (when he guesses the number), he is being redirected to the menu (using the main(args); method). In fact, String value cannot be writen in int input. So when i write 'end game' during the game cycle, it just crashes. What should i do?
Heres code of my game:
import java.util.Scanner;
public class TwoGames {
public static void main(String[] args) { // main menu
Scanner scan = new Scanner(System.in);
System.out.println("Choose the game\n Type 'letter' or 'number' to choose the game");
String UserAnswer = "";
UserAnswer = scan.next();
if (UserAnswer.equalsIgnoreCase("number")) {
number(args);
}else if(UserAnswer.equalsIgnoreCase("letter")){
letter(args);
}
scan.close();
}
public static void letter (String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";
int numberOfTries = 0;
do {
System.out.println("Guess the Letter");
char randomLetter = (char) (Math.random() * 26 + 65);
char enteredLetter = 0;
while(true){
enteredLetter = Character.toUpperCase(scan.next().charAt(0));
numberOfTries = numberOfTries + 1;
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
break;
}
else if(enteredLetter>randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too high");
}
else if(enteredLetter<randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too low");
}
}
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! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
public static void number(String[] args) { //heres the number guessing game
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";//variable to stop game
do {
int theNumber = (int)(Math.random() * 100 + 1);
int numberOfTries = 0;
do {
int guess = 0;
while (guess != theNumber) {
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt();
numberOfTries = numberOfTries + 1;
if (guess < theNumber)
System.out.println(guess + " is too low. Try again.");
else if (guess > theNumber)
System.out.println(guess + " is too high. Try again.");
else {
System.out.println(guess + " is correct. You win!");
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
}
}
} while (Stop.equalsIgnoreCase("end game"));
main(args);// this sends user to main menu
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! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
}
I am novice programmer, so yeah, thats might be a dumb question, because im learning. Anyway, any help and explanation would be useful.
To solve this problem, you should input a string, check if it equals to "End game" message and if not continue your code.
For example, replace this line:
guess = scan.nextInt();
In this code:
String input = scan.next();
if(input.equals("End game")){
main(args);
return;
}
guess = Integer.parseInt(input);
That code get a String input called input, check if he equals to "End game" and if not continue your guess loop.
I am writing a simple java guessing game, the game is supposed to randomly pick a number between 1 and 100 and then after you pick the correct number it asks you if you would like to play again. I know i should be able to use a Do while loop to ask if the user would like to play again, but every time I try I cannot make it work. This is my fully functional program without the do while loop. If someone could help me prompt the user if they would like to play again I would be very thankful. I am still very new to programming.
Also I apologize if the indenting isn't 100% correct.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame
{
public static void main (String [] args)
{
//Variables
Random randomNumber = new Random();
Scanner kbd = new Scanner(System.in);
int computerValue = randomNumber.nextInt(100);
int numberOfTries = 0;
int success = 0;
int guess = 0;
//Logic and While Loop
while (success ==0)
{
System.out.println("please enter an integer betwen 1 and 100 inclusive: ");
guess = kbd.nextInt();
numberOfTries++;
if (guess < 1 || guess > 100){
System.out.println("Invalid input");
}
else if (guess == computerValue){
success++;
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
}
else if (guess < computerValue){
System.out.println("Your guess is too low!");
}
else if (guess > computerValue){
System.out.println("Your guess is too high!");
}
}
}
}
Try this:
while(true) {
computerValue = randomNumber.nextInt(100);
numberOfTries = 0;
while (true) {
System.out.println("please enter an integer betwen 1 and 100 inclusive: ");
guess = kbd.nextInt();
numberOfTries++;
if (guess < 1 || guess > 100) System.out.println("Invalid input");
else if (guess == computerValue) {
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
// leave the first loop
break;
}
else if (guess < computerValue) System.out.println("Your guess is too low!");
else if (guess > computerValue) System.out.println("Your guess is too high!");
}
System.out.println("Do you want to play again? (1:Yes/2:No)");
// if input is not yes leave second loop
if(kbd.nextInt() != 1) break;
}
If you want to use a do while loop this would work.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
//Variables
Random randomNumber = new Random();
Scanner kbd = new Scanner(System.in);
int computerValue;
int numberOfTries = 0;
int success = 0;
int guess;
boolean playAgain;
//Logic and While Loop
do {
computerValue = randomNumber.nextInt(100);
guess = 0;
playAgain = false;
while (guess != computerValue) {
System.out.println("Please enter an integer betwen 1 and 100 inclusive: ");
guess = kbd.nextInt();
numberOfTries++;
if (guess < 1 || guess > 100) {
System.out.println("Invalid input");
} else if (guess < computerValue) {
System.out.println("Your guess is too low!");
} else if (guess > computerValue) {
System.out.println("Your guess is too high!");
}
}
success++;
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
System.out.println("Would you like to play again?");
switch (kbd.next()) {
case "yes":
playAgain = true;
break;
default:
break;
}
} while (playAgain);
System.out.println("Goodbye");
}
}
Prompt the user if he wants to play again at
else if (guess == computerValue) {
success++;
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
}
If the user inputs yes success--;
I am almost finished with my second Java assignment for class, but I am stuck on how to take the user's last choice and either play again or quit. Any ideas?
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
Random randomNumber = new Random();
int answer = randomNumber.nextInt(100) + 1;
int numberOfTries = 0;
Scanner userInput = new Scanner(System.in);
String userGuess = null;
boolean gameWin = false;
do {
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
while (userGuess.equals("yes"));
userInput.nextLine();
}
}
}
The problem is because you have userInput.nextLine() prompt for the user to play again or not outside of the game loop and it isn't assigned to any value. I am referring to this section...
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
while (userGuess.equals("yes"));
userInput.nextLine(); <---
}
To fix this problem you simply need to assign the final input call to userGuess and place it back into the game loop like so.
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
userGuess = userInput.nextLine();
}
while (userGuess.equals("yes"));
}
Doing this will assign the play again value you prompt the user for into the variable that your testing with the do-whileloop. In your original, you had the condition testing for a value that userGuess wasn't going to be storing and instead prompting the user for that option AFTER the loop would have been exited instead of inside where it needs to be.
To reset the values for the next game, you can simply move the variables' initialization into the game loop at the top like so...
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
Random randomNumber = new Random();
int numberOfTries, answer;
Scanner userInput = new Scanner(System.in);
String userGuess;
boolean gameWin;
do {
answer = randomNumber.nextInt(100) + 1;
gameWin = false;
userGuess = null;
numberOfTries = 0;
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
userGuess = userInput.nextLine();
}
while (userGuess.equals("yes"));
}
}
}
this way every time the game loops through, all the values will be reset at the beginning of the new game loop.
Also you should close the Random object and Scanner object at the end of the entire program using close() on each instance.
You need to initialize most of your variables and call userInput.nextLine(); inside your outer loop. Untested suggestion:
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
String userGuess = null;
do {
Random randomNumber = new Random();
int answer = randomNumber.nextInt(100) + 1;
int numberOfTries = 0;
Scanner userInput = new Scanner(System.in);
boolean gameWin = false;
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
userInput.nextLine();
while (userGuess.equals("yes"));
}
}
}
I'm new to Java so forgive me. I'm writing a small little Guessing Game program.
import java.util.Scanner;
public class GuessingGame {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int menuOption;
// Main Screen //
System.out.println("Guessing Game");
System.out.println("---------------------");
System.out.println("1.) Play Game");
System.out.println("2). Exit");
System.out.println();
while (true) {
System.out.print("Please select a menu option: ");
menuOption = userInput.nextInt();
if (menuOption == 2) {
System.out.println("Exiting the game. Thanks for playing!");
break;
} else if (menuOption == 1) {
System.out.println("Let's start the game!");
getRandomRange();
} else {
System.out.println("Sorry, that's not a valid option. Please try again.");
continue;
}
}
}
/**
* Determine the range of numbers to work with
*/
public static void getRandomRange() {
int min;
int max;
System.out.print("Choose a minimum number: ");
min = userInput.nextInt();
System.out.print("Choose a maximum value: ");
max = userInput.nextInt();
getRandomNumber(min, max);
}
public static void getRandomNumber(int min, int max) {
int randomNumber = (int) (Math.random() * (max - min + 1)) + min;
getAGuess(min, max, randomNumber);
}
public static void getAGuess(int min, int max, int randomNumber) {
int guess;
while (true) {
System.out.print("Guess a number between " + min + " and " + (max) + ": ");
guess = userInput.nextInt();
if (guess == randomNumber) {
System.out.println("Correct! The random number is: " + randomNumber);
break;
}
}
}
}
When I prompt the user to guess a number and the number is incorrect, I want to be able to flush immediately flush the input stream and enter another guess on the same line.
For example:
Guess a number between 0 and 5: I enter my guesses here on this one line only.
I could take the print out of the loop but in that case, if I enter an inccorect number, the cursor jumps to the next line.
Hope this makes sense. Thanks!
If your goal is only to clear the console, then you could do:
Runtime.getRuntime().exec("cls");
Or if you are on Linux or OS X:
Runtime.getRuntime().exec("clear");
Now if you add previous line that you wanted to keep, you will need to keep then in an Array and reprint after each clear.
This won't work in IDE's.
If you want a more system-independent way, there is a library named JLine (GitHub), which is designed for a better console usage. It actually contains a method clearScreen.
You could also do:
System.out.print("\033[H\033[2J");
This will clear the screen and return the cursor to the first row.
A quick and dirty solution...
public class Main {
public static final void main(String[] data) {
Scanner userInput = new Scanner(System.in);
int min = 0;
int max = 10;
int randomNumber = (int) ((Math.random() * max) + (min + 1));
while (true) {
System.out.print("Guess a number between " + min + " and " + max + ": ");
int guess = userInput.nextInt();
if (guess == randomNumber) {
System.out.println("Correct! The random number is: " + randomNumber);
break;
} else {
for (int i = 0 ; i < 25; i++) {
System.out.println();
}
}
}
}
}
i'm currently trying to create a while loop for my program, a Guessing game. I've set it up so the user can create a max value i.e 1-500 and then the user can proceed to guess the number. When the number has been guessed, the User can press 1, to close, anything else to continue running the loop again.
My problem, is that the code gives me an error when trying to continue the loop, no compiling errros
This is my Code:
import java.util.Random;
import java.util.Scanner;
public class Gættespil2
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Indsæt loftets højeste værdi : ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
while (win == false)
{
System.out.println(" Gæt et tal mellem 1 og "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Koldere, gæt igen");
}
else if (guess > TAL) {
System.out.println("Varmere, Gæt igen!!");
}
}
System.out.println(" Tillykke du vandt...endeligt!!! ");
System.out.println(" tallet var" + TAL);
System.out.println(" du brugte " + FORSØG + " forsøg");
System.out.println("Slut spillet? tast 1.");
System.out.println("tryk på hvadsomhelst for at spille videre");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Simple answer. You didn't initialize all the necessary values within your 'keepPlaying' loop before beginning a second round after the player successfully completed the first round. See annotations to your code, below:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Enter a maximum limit: ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
// *** LOOK HERE ***
// Reset the 'win' flag here, otherwise the player receives an
// automatic win on all subsequent rounds following the first
win = false;
while (win == false)
{
System.out.println("Guess the number between one and "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Colder, guess again!");
}
else if (guess > TAL) {
System.out.println("Warmer, guess again!");
}
}
System.out.println("You've found the number!");
System.out.println("The number was: " + TAL + ".");
System.out.println("You guessed " + FORSØG + " times.");
System.out.println("To quit, enter 1.");
System.out.println("Provide any other input to play again.");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Sorry for the translation into English -- I had to make sure I was reading things correctly. You might also want to substitute "higher" and "lower" for "warmer" and "colder." "Warmer" and "colder" tend to suggest a proximity to the correct answer, as opposed to the direction in which that correct answer lies.