Guessing Game, with a While loop - java

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.

Related

How and where do i put a try/catch for only entering numbers in a number guessing game?

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.

How do I get this value passed into main properly?

i am having trouble passing the value of "guess" into my main method. The
method that is trying to return guess just shows up as zero in the main.I have tried various things such as void methods and different returns but the guess value does not get updated in the while loop of the main even though, from what i am seeing, it should be getting updated from the method and passing it down to the guesses right below it.
import java.util.*;
public class assignment052 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int userGuess = 0;
int compNum = 0;
int guess = 0;
int totalGuesses = 0; //
int best = 9999; //
introduction();
int games = 0;
String playAgain = "y";
while(playAgain.equalsIgnoreCase("y")) {
System.out.println();
System.out.println("I'm thinking of a number between 1 and 100...");
games++;
guessNumber(console, userGuess, compNum, guess);
System.out.println(guess);
totalGuesses += guess;
System.out.println("Do you want to play again?");
Scanner newGame = new Scanner(System.in);
playAgain = newGame.next();
if (best > guess) { //
best = guess; //
}
}
result(games, totalGuesses, best);
}
// Method that introduces the game
public static void introduction() {
System.out.println("This program allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println("100 and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
}
// method to play 1 game
public static double guessNumber(Scanner console, int userGuess, int compNum, int guess) {
Random rand = new Random();
userGuess = console.nextInt();
guess = 1;
compNum = rand.nextInt(100)+1;
while(compNum != userGuess) {
if(compNum > userGuess) {
System.out.println("It's higher.");
} else {
System.out.println("It's lower.");
}
guess++;
userGuess = console.nextInt();
}
System.out.println("you got it right in " + guess + " guesses");
return guess;
}
// method for overall result
public static void result(int games, int totalGuesses, int best) {
System.out.println("Overall results:");
System.out.println();
System.out.println("Total games played : " + games);
System.out.println("Total guesses : " + totalGuesses);
System.out.println("Guesses per game : " + totalGuesses / games);
}
}

Java Guessing Game infinite loop

I'm having an issue with my code where the program will not play again, but
also will not end.
The code continues to loop in the inner while loop after a win or too many guesses.
Here is my code:
/**
* This program will prompt the user to guess a secret number
* This number will is between 1 and N, where N is a postive number
*
* #author: Perry Chapman
*/
import java.util.Scanner;
public class SecretNumber2
{
public static void main( String [] args )
{
int N;
int randomNumber;
int guess;
int tries, maxTries;
boolean win = false;
boolean playing = true;
int playAgain = 1;
tries = 0;
while(playing == true)
{
Scanner input = new Scanner( System.in );
System.out.println( "This is a guessing game." );
System.out.println( "What is the max number of tries: ");
maxTries = input.nextInt();
System.out.println( "Enter a value between 1 and 1000: " );
N = input.nextInt();
randomNumber = (int)(N * Math.random()) + 1;
while (win == false)
{
System.out.println( "Enter your guess: " );
guess = input.nextInt();
tries++;
if (guess == randomNumber)
{
System.out.println( "Congratulations! The number of guesses it took you was " + tries );
win = true;
System.out.println("Would you like to play again? \n (1)Yes or (2)No: ");
playAgain = input.nextInt();
if(playAgain == 1) {
playing = true;
}
else if (playAgain == 2) {
playing = false;
}
tries = 0;
}
else if(guess < randomNumber)
System.out.println( "Too low, guess again." );
else if(guess > randomNumber)
System.out.println( "Too high, guess again." );
else if(tries == maxTries)
{
System.out.println("You have exceeded the max number of tries. \nYou lose.");
System.out.println("\nWould you like to play again?\n (1)Yes or (2)No: ");
playAgain = input.nextInt();
if(playAgain == 1) {
playing = true;
}
else if(playAgain == 2) {
playing = false;
}
tries = 0;
}
}
}
}
}
Andrew is right, in order to loop the condition need to be true.The if else statement need to be in the right order. Here is a fix, I hope it will help.
public static void main(String[] args) {
int N;
int randomNumber;
int guess;
int tries, maxTries;
boolean lose;
boolean playing = true;
int playAgain;
tries = 0;
while (playing) {
Scanner input = new Scanner(System.in);
System.out.println("This is a guessing game.");
System.out.println("What is the max number of tries: ");
maxTries = input.nextInt();
System.out.println("Enter a value between 1 and 1000: ");
N = input.nextInt();
randomNumber = (int) (N * Math.random()) + 1;
lose = true;
while (lose) {
System.out.println("Enter your guess: ");
guess = input.nextInt();
tries++;
if (guess == randomNumber) {
System.out.println("Congratulations! The number of guesses it took you was " + tries);
lose = false;
System.out.println("Would you like to play again? \n (1)Yes or (2)No: ");
playAgain = input.nextInt();
if (playAgain == 1) {
playing = true;
} else if (playAgain == 2) {
playing = false;
}
tries = 0;
} else if (tries == maxTries) {
System.out.println("You have exceeded the max number of tries. \nYou lose.");
System.out.println("\nWould you like to play again?\n (1)Yes or (2)No: ");
playAgain = input.nextInt();
if (playAgain == 1) {
playing = true;
} else if (playAgain == 2) {
playing = false;
}
lose = false;
tries = 0;
} else if (guess < randomNumber) {
System.out.println("Too low, guess again.");
} else if (guess > randomNumber) {
System.out.println("Too high, guess again.");
}
}
}
}
I think you have two issues.
The first is that after successfully guessing the number you never set win back to false. So you won't ever enter the inner while loop a second time.
The second is the ordering of the if/else if statements, there is never a scenario where a guess can reach the final else if. Every situation will validate as true in one of the previous three ifs.
/**
* This program will prompt the user to guess a secret number
* This number will is between 1 and N, where N is a postive number
*
* #author: Perry C
*/
import java.util.Scanner;
public class SecretNumber
{
public static void main( String [] args )
{
int N;
int guess;
int playAgain;
int tries;
int maxTries;
playAgain = 1;
tries = 0;
Scanner input = new Scanner( System.in );
while(playAgain == 1)
{
boolean win = false;
System.out.println( "This is a guessing game." );
System.out.println( "How many guesses would you like?" );
maxTries = input.nextInt();
System.out.println( "Enter a value between 1 and 1000: " );
N = input.nextInt();
int randomNumber = (int)(N * Math.random()) + 1;
while (win == false)
{
System.out.println( "Enter your guess: " );
guess = input.nextInt();
tries++;
if(guess == randomNumber)
{
System.out.println( "Congratulations! The number of guesses it took you was \t" + tries );
win = true;
System.out.println( "Would you like to play again(1 or 2):" );
playAgain = input.nextInt();
tries = 0;
}
else if(guess < randomNumber)
System.out.println( "Too low, guess again." );
else if(guess > randomNumber)
System.out.println( "Too high, guess again." );
if(tries == maxTries)
{
System.out.println( "You have exceeded the max number of tries. \n You lose." );
System.out.println( "Would you like to play again(1 or 2):" );
playAgain = input.nextInt();
tries = 0;
win = true;
}
}
}
}
}
Found the issue, thought I would post the answer in case anyone else might stumble on this thread! Thanks for the help!

Do while loop for guessing game

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

How to ask user to Play Again....Guess Game

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"));

Categories