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--;
Related
import java.util.Random;
import java.util.Scanner;
public class Activity3 {
public static void main(String[] args) {
//Variables
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10);
do {
System.out.println("Guess the random generated number of the machine from 1-10");
int guess = input.nextInt();
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
} else if (guess <= 0 && guess >= 11) {
System.out.println("Invalid Number!");
}
if (guess > 1 && guess < 10){
System.out.println("You Lose:<");
}
System.out.println("Do you want to try again?");
} while (input.next().equalsIgnoreCase("YES"));
input.close();
}
}
If I guess the correct number it outputs " you win!".
If I guess wrong it outputs "you lose". But If I guess a number that isn't in 1-10 it doesn't output the "Invalid Number" and just proceeds to output the "Do you want to try again?".
Random#nextInt(int) will return a value from 0 to bound - 1, so it's possible that the guess could be 0 in your code. You'd correct this by adding 1 to the guess, for example int num = Machine.nextInt(10) + 1;
Look at your logic...
else if(guess <= 0 && guess >= 11) {
if guess <= 0 AND guess >= 11 ... well, that's impossible.
I would change your logic flow, focusing on "happy paths" first.
That is, is the input within the acceptable range? If so, is guess == num if so, you win, otherwise print error messages.
For example...
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10) + 1;
boolean done = false;
do {
System.out.println("Guess the random generated number of the machine from 1-10");
// Read the WHOLE line of text, removing the new line from the
// buffer which would otherwise be left by Scanner#nextInt
// and would cause no end of issues
String text = input.nextLine();
try {
// Try and parse the text to an int
int guess = Integer.parseInt(text);
if (guess >= 1 && guess <= 10) {
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
num = Machine.nextInt(10) + 1;
System.out.println("Would you like to play another game? (Yes/No)");
} else {
System.out.println("Incorrect, guess again");
System.out.println("Do you want to try again? (Yes/No)");
}
// Prompt the user to try again or play another game
text = input.nextLine();
done = !"yes".equals(text.toLowerCase());
} else {
System.out.println("Out of range");
}
} catch (NumberFormatException exp) {
System.out.println("Not a valid number");
}
} while (!done);
public class NewClass12 {
public static void main(String[] args) {
Random generator = new Random();
int numberToGuess = generator.nextInt(10 - 1) + 1;
int yourGuess;
Scanner input = new Scanner(System.in);
int guess = 0;
boolean win = false;
while (!win) {
System.out.println("Guess a number between 1 and 10: ");
yourGuess = input.nextInt();
guess++;
if (yourGuess < 1 || guess > 10) {
System.out.println("Guess is out of range! Enter a number between 1 and 10");
continue;
}
if (yourGuess == numberToGuess) {
win = true;
break;
}
if (yourGuess < numberToGuess) {
System.out.println("Your guess is too low");
} else {
System.out.println("Your guess is too high");
}
}
if (win) {
System.out.println("You win!");
System.out.println("The number was " + numberToGuess);
System.out.println("It took you " + guess + " tries.");
}
}
}
so, this is my code for a number guessing game. everything works fine so far execpt if i enter a letter as an input my code crashes. I guess i have to use a try/catch ? If yes where and how do i write it. I am a beginner so have mercy.
I this case, I would put the try catch wrapping where you read the user's input, like so:
public class NewClass12 {
public static void main(String[] args) {
Random generator = new Random();
int numberToGuess = generator.nextInt(10 - 1) + 1;
int yourGuess;
Scanner input = new Scanner(System.in);
int guess = 0;
boolean win = false;
while (!win) {
System.out.println("Guess a number between 1 and 10: ");
try{
yourGuess = input.nextInt();
guess++;
if (yourGuess < 1 || guess > 10) {
System.out.println("Guess is out of range! Enter a number between 1 and 10");
continue;
}
if (yourGuess == numberToGuess) {
win = true;
break;
}
if (yourGuess < numberToGuess) {
System.out.println("Your guess is too low");
} else {
System.out.println("Your guess is too high");
}
} catch (InputMismatchException err){
System.out.println("The input must be a number!");
input.next();
}
}
if (win) {
System.out.println("You win!");
System.out.println("The number was " + numberToGuess);
System.out.println("It took you " + guess + " tries.");
}
}
}
Note that we need the input.next() within the catch, in order to consume the invalid input, so it won't be in a loop.
So I've been working on this and it works fine, only problem is that after you guess a number that's not between 1 and 100, it goes onto the next guess when the try shouldn't count against you. I've attached a picture of what the output SHOULD look like.
Do I need a 'for' statement or a boolean variable?
And here is my code:
Random generator = new Random();
//import the scanner for prompt
Scanner input = new Scanner(System.in);
//integers for the secret number, input guess of the secret number, tries and limit to tries
int numberToGuess = 1 + generator.nextInt(100);
int numberOfTries = 1;
int limit = 10;
int guess;
//prompt user to enter a number to guess
System.out.println("You have 10 tries to guess a number between 1 and 100");
//start of while loop
while (numberOfTries <= 10) {
System.out.print("Guess number " + numberOfTries + ": ");
guess = input.nextInt();
//if else statements (outputs)
if (guess < numberToGuess)
System.out.println("Your guess is too low. Try again.");
else if (guess > 100)
System.out.println("Guesses should be between 1 and 100.");
else if (guess > numberToGuess)
System.out.println("Too high. Try again.");
else if (guess == numberToGuess) {
System.out.println("Congratulations! You have correctly guess the number in " + numberOfTries + " tries");
System.exit(0);
} else {
System.out.println("Sorry, you did not guess the guess the answer in 10 tries");
System.out.println("The number was " + numberToGuess);
//break to end while loop
break;
}
numberOfTries++;
// If statement after executing the while loop the output if user loses and answer to secret number
if (numberOfTries > 10) {
System.out.println("Sorry, you did not guess the guess the answer in 10 tries");
System.out.println("The number was " + numberToGuess);
}
}
Don't increment numberOfTries++; if they guess a number outside of the range. Put the increment inside the if statements
Try using a nested do-while loop inside your primary while loop:
//start of while loop
while(numberOfTries <= 10){
//get a valid guess
do{
boolean valid = true;
System.out.print("Guess number " + numberOfTries + ": ");
guess= input.nextInt();
//if else statements (outputs)
if (guess < numberToGuess){
System.out.println("Your guess is too low. Try again.");
valid = false;
}
else if (guess > 100){
System.out.println("Guesses should be between 1 and 100.");
valid = false;
}
while (!valid);
//handle the valid guess
}
Here's how I'd do it. You tell me which one you prefer:
import java.util.Random;
import java.util.Scanner;
/**
* Created by Michael
* Creation date 3/4/2016.
* #link https://stackoverflow.com/questions/35809392/while-loop-in-java-number-guess
*/
public class NumberGuess {
public static final int MIN_VALUE = 1;
public static final int MAX_VALUE = 100;
public static final int MAX_TRIES = 10;
public static void main(String[] args) {
Random generator = new Random();
Scanner input = new Scanner(System.in);
String playAgain;
do {
int answer = MIN_VALUE + generator.nextInt(MAX_VALUE);
System.out.println(String.format("You have %d tries to guess a number between %d and %d", MAX_TRIES, MIN_VALUE, MAX_VALUE));
boolean correct = playGuessingGame(input, answer);
if (!correct) {
System.out.println(String.format("The number was %d", answer));
}
System.out.print("Play again? [Y/N]: ");
playAgain = input.nextLine();
} while ("Y".equalsIgnoreCase(playAgain));
}
public static boolean playGuessingGame(Scanner input, int answer) {
boolean correct = false;
int numTries = 0;
do {
System.out.print(String.format("Guess %d: ", ++numTries));
int guess = Integer.parseInt(input.nextLine());
if (guess < MIN_VALUE) {
System.out.println(String.format("Guess %d is below minimum %d", guess, MIN_VALUE));
} else if (guess > MAX_VALUE) {
System.out.println(String.format("Guess %d is above maximum %d", guess, MAX_VALUE));
} else if (guess < answer) {
System.out.println(String.format("Guess %d is too low. Try again.", guess));
} else if (guess > answer) {
System.out.println(String.format("Guess %d is too high. Try again.", guess));
} else {
System.out.println("Woo hoo! You got it right!");
correct = true;
break;
}
} while (numTries < MAX_TRIES);
return correct;
}
}
You and your professor realize that it's almost impossible to lose this game. Right?
A bisection strategy says you can always get the right answer with 10 tries. Make that number smaller for a challenge.
increamenting should be done inside the if statemnt :D
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"));
}
}
}
Im fairly new to java and im having trouble getting this to loop? The code works fine, its just that after the user guesses correctly the code stops.
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class Chapter3HighLow {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random(); //gives random numbers each time
int correctNum = random.nextInt(100);
int NumberOfTries = 0; // tells how many guesses it took
while (true) {
System.out.println("Hi! Please enter a number between 1-100! (if you would like to quit, please press -1)");
int guess1 = input.nextInt();
NumberOfTries++; //user enters their guesses
if (guess1 == (-1)) {
break; //breaks the loop if the user enters -1
}
if(guess1 < correctNum){
System.out.println("The number inserted is too low!");
}
else if(guess1 > correctNum){
System.out.println("The number inserted is too high!");
}
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries"); // Tells how many tries it took
}
}
}
}
I'm not entirely sure what you're asking, however, from what I can understand, you are looking to get your game to loop continuously until the user wants to stop playing. So what you are looking for is a method which gives the user a choice whether they want to play again. My suggesting is using boolean. The following code demonstrates this for your example:
import java.util.Random;
import java.util.Scanner;
public class Chapter3HighLow {
private static boolean playAgain(){
Scanner sc = new Scanner(System.in);
String usrInput = "";
System.out.println("Play again? (Y/N)");
usrInput = sc.next();
if(usrInput.equalsIgnoreCase("Y")){
return true;
}
else if(usrInput.equalsIgnoreCase("N")){
return false;
}
else{
return false;
}
}
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random(); //gives random numbers each time
int correctNum = random.nextInt(100);
int NumberOfTries = 0; // tells how many guesses it took
int guess1 = 0;
do{
do{
System.out.println("Please guess a number between 1-100!");
guess1 = input.nextInt();
NumberOfTries++; //user enters their guesses
if (guess1 == (-1)) {
break; //breaks the loop if the user enters -1
}
if(guess1 < correctNum){
System.out.println("The number inserted is too low!");
}
else if(guess1 > correctNum){
System.out.println("The number inserted is too high!");
}
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries"); // Tells how many tries it took
}
}while(guess1 != correctNum);
correctNum = random.nextInt(100);
NumberOfTries = 0;
}while(playAgain() == true);
}
}
Read more about methods here.
Read more about the boolean data type here.
Your final else appears to be missing a break. Like
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries");
break; // <-- add this.
}
or you might make that the while condition. Something like,
int guess1 = -1;
while (guess1 != correctNum) {
System.out.println("Hi! Please enter a number between 1-100! "
+ "(if you would like to quit, please press -1)");
guess1 = input.nextInt();
if (guess1 == (-1)) {
break;
}
NumberOfTries++;
if (guess1 < correctNum) {
System.out.println("The number inserted is too low!");
} else if (guess1 > correctNum) {
System.out.println("The number inserted is too high!");
} else if (guess1 == correctNum) {
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries");
}
}
Does it really stop after guessing it right ?