I'm fairly new to java and I was wondering how could I reset this game to ask another number after the user guessed it correctly?
Here's my code so far:
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
if(guess == -1){
System.out.print("Thank you for playing the game!");
break;
}
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
}
Just wrap your entire code (except for the scanner initialization) in a while loop that is always true. That way, when one game ends, it will start a new one. Then, instead of breaking your game's while loop when the user enters a -1, just use System.exit(0), which will end your program with a status code of 0, indicating that the program executed successfully.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
while (true) {
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100) {
if (guess == -1) {
System.out.print("Thank you for playing the game!");
System.exit(0);
}
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
} else if (guess < a) {
System.out.print("The number is higher. Try again: ");
} else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
}
Wrap your code in a while (true) this will keep on running your code for ever and ever. Make sure you are also updating your random a after every game and your count. Then from there just check if guess is ever -1 and return when it is. When you call return it will end the method which ends your game.
Scanner keyboard = new Scanner(System.in);
while (true){
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess==-1){
System.out.print("Thank you for playing the game!");
return;
}else if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
You need to:
move your end game condition in the while condition like this while(guess != -1)
move the welcome greetings inside the loop
move the thank you greeting after the game loop is done
reset count and a when the user won a game in order to start fresh
reset guess on every iteration
Now even if the player guesses the number, the loop does not end and the game loop can be stopped only intentionally (by entering -1 = current break condition):
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
while (guess != -1) {
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
a = 1 + (int) (Math.random() * 99);
System.out.println("Congratulations. You guessed the number in " + count + " tries!");
count = 0;
}
guess = 0;
}
System.out.print("Thank you for playing the game!");
}
The code can be refactored even more, for example extract functionality into functions in order to make the code more readable. This also leads to easier maintanence should the variables change or should more conditions come. For example the code can be refactored like this:
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int a = 0;
int count = 0;
int guess = 0;
startNewGame();
System.out.println("Welcome to the Number Guessing Game");
while (guess != -1) {
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in " + count + " tries!");
startNewGame();
}
resetGuess();
}
System.out.print("Thank you for playing the game!");
}
private static int generateNewA() {
return 1 + (int) (Math.random() * 99);
}
private static void startNewGame() {
a = generateNewA();
count = 0;
}
private static void resetGuess() {
guess = 0;
}
}
Another solution is to use two nested loops, but IMO for this case loop in a loop is too much and makes the source unnecessary complex.
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);
Ok I need help on a school assignment that I'm currently stuck on and I need a lot of help. I have tried to do this for hours and still cant figure out on how to do this assignment. This is my code below.
I'm trying to create a guessing game. What I'm stuck on is how I'm suppose to loop the number of 10 guesses and no more. I tried it and it gives me an infinite loop.
What im trying to create:
A number from 1 and 100 is picked and the player does not know what the number is.
The player is asked to guess a number from 1 to 100.
They have 10 chances to guess the right number.
If the player does not guess the correct number within 10 guesses then the player loses the game.
You let them know if their guess is too low or too high to help them narrow down their guesses to eventually guess the right number before their 10 guesses are used up.
import java.util.Scanner;
import java.util.Random;
public class GuessGame3
{
public static void main (String[] args){
int num1;
int count=0;
int Guess=0;
Random generator = new Random();
Scanner scan = new Scanner(System.in);
//get generator
num1 = generator.nextInt(100) + 1;
while (Guess != num1){
System.out.println("Enter a number between 1 and 100");
Guess = scan.nextInt();
count++;
while (count > 10)
System.out.println("Sorry you didnt guess in 10 trues its been " + count + " tries");
if ( Guess > num1)
{
System.out.println("Lower!");
}
else if (Guess < num1)
{
System.out.println("Higher");
}
else
System.out.println("Congratz with " + count + " amount of tries");
}
}
}
I recommend putting the checks if the guess is as part of the first while loop, not a nested one.:
while (count < 10){
System.out.println("Enter a number between 1 and 100");
Guess = scan.nextInt();
count++;
if ( Guess > num1)
{
System.out.println("Lower!");
}
else if (Guess < num1)
{
System.out.println("Higher");
}
else {
break;
}
}
if(count < 10) {
System.out.println("Congrats! You have completed it in " + count + " tries!");
} else {
System.out.println("Sorry you have run out of your 10 guesses!");
}
There might be some errors here, but you should get the gist.
Problem lies with the loop and in the order you have validated the total number of tries and the Guess match. Try the below
import java.util.Scanner;
import java.util.Random;
public class TestGame
{
public static void main(String[] args)
{
int num1;
int count = 0;
int Guess = 0;
int maxAllowedRetries = 10;
Random generator = new Random();
Scanner scan = new Scanner(System.in);
//get generator
num1 = generator.nextInt(100) + 1;
while(count <= maxAllowedRetries)
{
if(count == maxAllowedRetries)
{
System.out.println("Sorry you have reached maximum number of retries!");
break;
}
count++;
System.out.println("Enter a number between 1 and 100");
Guess = scan.nextInt();
if(Guess == num1)
{
System.out.println("Great you got it Right!");
break;
}
System.out.println("Sorry you didnt guess right. Its been " + count + " tries");
if(Guess > num1)
{
System.out.println("Lower!");
}
else if(Guess < num1)
{
System.out.println("Higher");
}
}
}
}
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'm kinda new to java and I was wondering how to loop this code until someone enters -1 and how to add "out of bounds" if the user enters number not between 0-100?
here's my code so far:
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
}
You can check for the bounds within the for loop. In order to stop further checks, you can iterate to the next loop through the continue call. Otherwise, if you actually want to break out of the loop, use the break call (for the -1 case).
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
if(guess == -1)
break;
System.out.println("Out of bounds");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
System.out.println("Thank-you for playing the game!!");
You want to do some code while something is not = to -1. In java, we use
!=
to represent not equal. So, try this code with the do while in mind:
do{
guess = keyboard.nextInt();
count++;
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
\\Here comes the **while**
} while (guess != a && keyboard.in != -1)
The while states that when guess is not a AND the user has not entered -1. This is the only way that the do can be executed.
Thats it! I suggest you read more about math operations and loops.
Best of luck,
{Rich}
First of all, I'd like to say that I am REALLY new to all of this... I've tried learning as much as I can, so apologies if any of my code seems ridiculous or all-over-the-place, but I needed somewhere to start. (By the way, credit to the very base of this code goes to CrossCoastGaming: http://tinyurl.com/kktyq4e).
Now to the matter at hand. I have improved (for lack of a better word) on the coding that the man in the video shows, by adding several different phrases, making use of variables and adding a try counter. Here is my code:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static int number, guess, tryCount, replay;
public static int maxValue =1;
public static Scanner scan;
public static Random rand;
public static void main(String args[]) {
scan = new Scanner(System.in);
rand = new Random();
System.out.print("Enter a maximum number: ");
while(maxValue < 2)
maxValue = scan.nextInt();
number = rand.nextInt(maxValue);
System.out.print("Guess a number from 1 to " + maxValue + ": ");
while (guess != number) {
guess = scan.nextInt();
tryCount++;
if (guess < 1) {
System.out.print("Guess is not positive. Try again: ");
}else if (guess < number) {
System.out.print("Too low! Try again: ");
}
if (guess > maxValue) {
System.out.println("Guess is higher than " + maxValue + ". Try again: ");
}else if (guess > number) {
System.out.print("Too high! Try again: ");
}
}
if (tryCount == 1) {
System.out.println("Nailed it! It only took you 1 try!");
}
else {
System.out.println("Nailed it! It took you " + tryCount + " tries.");
}
System.out.println("Type 0 to play again. Type 1 to quit.");
if (replay == 1) {
replay = scan.nextInt();
}
}
}
Ok, so hopefully that gives anyone who knows what they're doing an idea of my goal. Now, as you can see by this line:
if (replay == 1) {
replay = scan.nextInt();
}
I would like to write a way so people can replay the game without having to reboot the file. I already have an idea of what I kind of would like to do, but I've searched everywhere and can't seem to find out what to continue with after this point. I'm sure that I'm missing something. Any help would be greatly appreciated.
You can use a do-while loop to achieve this:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static int number, guess, tryCount, replay;
public static int maxValue = 1;
public static Scanner scan;
public static Random rand;
public static void main(String args[]) {
scan = new Scanner(System.in);
rand = new Random();
do { // start of do-while loop
tryCount = 0; // reset tryCount
System.out.print("Enter a maximum number: ");
while(maxValue < 2) {
maxValue = scan.nextInt();
}
number = rand.nextInt(maxValue);
System.out.print("Guess a number from 1 to " + maxValue + ": ");
while (guess != number) {
guess = scan.nextInt();
tryCount++;
if (guess < 1) {
System.out.print("Guess is not positive. Try again: ");
} else if (guess < number) {
System.out.print("Too low! Try again: ");
}
if (guess > maxValue) {
System.out.println("Guess is higher than " + maxValue + ". Try again: ");
} else if (guess > number) {
System.out.print("Too high! Try again: ");
}
}
if (tryCount == 1) {
System.out.println("Nailed it! It only took you 1 try!");
} else {
System.out.println("Nailed it! It took you " + tryCount + " tries.");
}
do { // check the user's input
System.out.println("Type 0 to play again. Type 1 to quit.");
replay = scan.nextInt();
if (replay != 0 && replay != 1) {
System.out.println("Input not recognized.");
}
} while (replay != 0 && replay != 1);
} while (replay == 0); // end of do-while loop
}
}
do-while loops are always executed at least once. The condition is checked at the end of the loop.