I am writing a simple guessing game program where the user will input a number to try and guess a randomly generated number.
If they get the number right I want to give them the option to play again.
Here is my code:
public class GuessingGame {
private Random num = new Random();
private int answer = num.nextInt(10);
private int guess;
private String playAgain;
public void inputGuess(){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
}while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = input.nextLine();
if(playAgain == "Y" || playAgain == "y"){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
}
}
}
The game plays through but when the user is prompted to play again nothing happens?
Any suggestions?
Here is the completed code, fully working and tested... without using recursion.. and everything fixed.
public static void main(String[] args)
{
String playAgain = "";
Scanner scan = new Scanner(System.in);
do
{
ClassName.inputGuess();
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = scan.nextLine();
}
while(playAgain.equalsIgnoreCase("Y"));
System.out.println("Thanks for playing!");
}
public void inputGuess()
{
Random num = new Random();
int answer = num.nextInt(10)+1;
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
do
{
if (guess < 1 || guess > 10)
{
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}
else
if (guess > answer)
{
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}
else
if (guess < answer)
{
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
input.nextLine();
}
while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
}
Do the following and your code will work :
Replace all input.nextInt(); with Integer.parseInt(input.nextLine());
Replace (playAgain == "Y" || playAgain == "y") with (playAgain.equalsIgnoreCase("Y"))
Initialise answer inside inputGuess() in starting instead.
Replace the body of if(playAgain.equalIgnoreCase("Y")) with inputGuess();
When you enter integer value through console it also contain a \n(next line) in it. But when you use nextInt(), it doesn't read this \n, but then when you tried to get next line with input.nextLine(), it looks for \n(next line) which is already there from integer entry and having nothing after that. Code look for "Y" or "y" and breaks because it doesn't found any of them.
That is why Integer.parseInt(input.nextLine()); works here
Here is the code:
private Random num = new Random();
private int answer = num.nextInt(10) +1;
private int guess;
private String playAgain;
Scanner input = new Scanner(System.in);
public void inputGuess(){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
if(guess == answer) {
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = input.nextLine();
}
}while (!playAgain.equals("Y") && !playAgain.equals("y"));
}
You just need to introduce the winning/losing logic inside the while, and the condition will be the ending/continue flag.
Another thing is always remember when comparing strings to use the equals method, since the == will compare the object reference and not the String value, in some cases == will return true for equal string since how JVM stores the Strings, but to be sure always use equals.
Try something like this:
public void inputGuess(){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
playAgain = "Y";
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
if(guess == answer)
{
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or N to quit: ");
input.nextLine();
playAgain = input.next();
answer = num.nextInt(10);
guess = -1;
if(!playAgain.equalsIgnoreCase("N"))
{
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
}
}
}while (!playAgain.equalsIgnoreCase("N"));
}
You need your code for checking if they want to play again inside the loop. This way you wait until they have guessed the number correctly then ask if they want to play again. If they do you restart the process if they don't you exit the loop.
Some of the solution I see above aren't correct. The random number, you need to add 1 to get between 1 and 10, also you need to compare with equals. I use case insensitive here.
The following code works as you need it.
import java.util.Random;
import java.util.Scanner;
public class Test2 {
private static Random num = new Random();
private static int answer = 0;
private static int guess;
private static String playAgain;
public static void main(String[] args) {
inputGuess();
}
// Guess Method.
public static void inputGuess(){
// create answer.
answer = 1+ num.nextInt(10);
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
}while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = input.nextLine();
if( playAgain.equalsIgnoreCase("Y") ){
inputGuess();
}
}
}
By now, you would have already guessed the right way to do it. Here is how I will approach it
public class Test {
public static void main (String...a) {
inputGuess();
}
public static void inputGuess() {
Scanner input = new Scanner(System.in);
String playAgain = "Y";
int guess;
Random ran = new Random();
int answer = ran.nextInt(10) + 1;
while (playAgain.equalsIgnoreCase("Y")) {
System.out.println("Enter a number between 1 and 10 as your first guess: " + answer);
guess = input.nextInt();
do {
if (guess < 1 || guess > 10) {
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
} else if (guess > answer) {
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
} else if (guess < answer) {
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
} while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
input.nextLine();
playAgain = input.nextLine();
answer = ran.nextInt(10) + 1
}
}
}
This code can serve your purpose...
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
private Random num = new Random();
private int answer ;
private int guess;
private String playAgain;
public void inputGuess()
{
answer = num.nextInt(11);
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
do {
if (guess < 1 || guess > 10) {
System.out
.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
} else if (guess > answer) {
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
} else if (guess < answer) {
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
} while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
do
{
playAgain = input.nextLine();
}while(playAgain.length()<1);
if (playAgain.trim().equalsIgnoreCase("y"))
{
inputGuess();
}
else
{
System.out.println("Good Bye!!!");
}
}
public static void main(String[] args) {
new GuessingGame().inputGuess();
}
}
one issue :
Do not compare the content of two strings by == which just
you should use equals()
Imagine the right answer is one in this case
Follow this as your blue print sample
int answer = 0;
String yes = "";
Scanner input = new Scanner(System.in);
do{
do{
System.out.println("Enter your number");
answer = input.nextInt();
} while ( answer != 1);
System.out.println("Would you like to play again?");
yes = input.next();
} while ( yes.equalsIgnoreCase("yes"));
output:
Related
I'm working on a homework problem of creating a guessing game. I've got that part working, but we have to validate the input. I've tried using hasNextInt, but I keep getting an error saying "int cannot be dereferenced" and points to the "!guess.hasNextInt" code.
I've tried many iterations, but I still get the same error. The code I'm including is just my most recent try.
How do I get hasNextInt to work or how else should I validate the input?
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
int num = (int) (Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (guess != num) {
System.out.print("Guess a number between 1 and 100: ");
guess = input.nextInt();
//Validates input
while (!guess.hasNextInt()) {
System.out.println("Invalid response, try again.");
in.next();
}
if (guess == num)
System.out.println("Correct!");
else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
}
}
}
i fixed the code:
public static void main(String[] args) {
int num = (int) (Math.random() * 101);
System.out.println(num);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (guess != num) {
System.out.print("Guess a number between 1 and 100: ");
guess = input.nextInt();
if (guess == num) {
System.out.println("Correct!");
break;}
else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
//Validates input
while (!input.hasNextInt()) {
System.out.println("Invalid response, try again.");
input.next();
}
}
}
if the user guessed the number the game ends using break
in while (!guess.hasNextInt()) you were using a integer where it's expect the Scanner input
If you want to parse your number you can use Integer.parseInt() method as shown. Also you are using hasNextInt() incorrectly. You are also not storing in.next() value in any variable.
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
int num = (int)(Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (true) {
System.out.print("Guess a number between 1 and 100: ");
String numberString = input.nextLine();
//Validates input
try {
guess = Integer.parseInt(numberString);
if (guess == num) {
System.out.println("Correct!");
break;
} else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
} catch (Exception e) {
System.out.println("Invalid response, try again.");
}
}
}
}
When I compile, that try to enter (y) to play again my do - while is not working, it takes me out of the loop.
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
int guessNumber = 0;
do
{
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
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.");
scan.close();
}
}
Change the code as below: (You just need to update the variables inside the loop)
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = 0;
int guessNumber = 0;
do
{
// new lines to be added
theNumber = (int)(Math.random() * 100 + 1);
guessNumber = 0;
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
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.");
scan.close();
}
Here is the execution of code on Jshell:
The reason the program is not working is because the do-while loop does one iteration before it gets to the "while" part. In your case, the program successfully finishes the loop after a user correctly guesses the number. Your program breaks because after that you are requiring the user to enter 'y' to continue endlessly without letting them guess a number. If they guess a number, the program terminates.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to write a program that randomly generates a number and the user tries to guess the number. The program keeps count of how many tries it took to guess the right number. The issue that I am having is getting past the while loop. When I run the program, it doesn't go past the while loop until I hit -1, in which case it outputs "Your number is too low". I am not real sure where I went wrong.
import java.util.Scanner;
import java.util.Random;
public class DoGuessingGame
{
public static void main(String[] args)
{
int number1, userInput; //assign vars
int tries = 0;
Random rand = new Random();
Scanner keyboard = new Scanner(System.in); //define Random and scanner input
System.out.println("Welcome to the Guessing Game!");
System.out.println("-----------------------------");
number1 = rand.nextInt(20) + 1;
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
}
while(userInput != -1);
{
if (userInput > 0 && userInput < 21)
{
if(userInput == number1)
{
System.out.println("That is the correct number");
tries++;
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
}
else if(userInput > number1)
{
System.out.println("Your number is too high");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
else if(userInput < number1);
{
System.out.println("Your number is too low");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
}
else
{
System.out.println("Please enter a number between 1 and 20");
}
}
System.out.println("The number of tries: " + tries);
}
}
Your nesting and placement of braces is confusing. No wonder you're having problems.
Learn to pay more attention to style and readability.
I did not compile or run your code. I didn't think too deeply to see if you did this correctly. But I might do it more like this:
import java.util.Scanner;
import java.util.Random;
public class DoGuessingGame
{
public static void main(String[] args) {
int number1, userInput; //assign vars
int tries = 0;
Random rand = new Random();
Scanner keyboard = new Scanner(System.in); //define Random and scanner input
System.out.println("Welcome to the Guessing Game!");
System.out.println("-----------------------------");
number1 = rand.nextInt(20) + 1;
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
if (userInput > 0 && userInput < 21) {
if(userInput == number1) {
System.out.println("That is the correct number");
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
userInput = -1;
} else if(userInput > number1) {
System.out.println("Your number is too high");
System.out.println("Please try again");
} else if(userInput < number1) {
System.out.println("Your number is too low");
System.out.println("Please try again");
}
} else {
System.out.println("Please enter a number between 1 and 20");
}
} while(userInput != -1);
System.out.println("The number of tries: " + tries);
}
You have an extra pair of braces directly after your do-while loop, as well as a semicolon directly after an if-statement which will alter the flow of your program.
else if(userInput < number1);
Your do/while loop is not doing what you think. You have:
do {
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
} while(userInput != -1);
Code below this point is executing after the do while loop, hence userInput will always be -1 when you reach here!
I think your do.... while loop should look like this
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
if (userInput > 0 && userInput < 21)
{
if(userInput == number1)
{
System.out.println("That is the correct number");
tries++;
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
}
else if(userInput > number1)
{
System.out.println("Your number is too high");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
else if(userInput < number1);
{
System.out.println("Your number is too low");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
}
else
{
System.out.println("Please enter a number between 1 and 20");
}
}
while(userInput != -1);
I am doing a guessing game where in I can input 1-100 but I am having a trouble in only accepting numbers if I typed a letter when I first run the program it will give me error and execute the program instantly image herebut if ityped number after I start the program and type letter next it give me a wrong message it should only display message saying "invalid input".image here Any suggestion thanks.
package m1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class M1{
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int between = 100;
int secretNumber = (int)(Math.random()*between);
int inputNum = 0;
int guesses = 0;
System.out.println("Please enter your guess: ");
inputNum = Scanner.nextInt();
guesses++;
while (inputNum != secretNumber) {
try {
// number too high or too low
if (inputNum > 100 || inputNum < 1) {
System.out.println("Out of Range!");
System.out.println("Enter a guess between 1 and " + between + ".");
inputNum = Scanner.nextInt();
}
// less than secretNumber
if (inputNum < secretNumber) {
System.out.println("Too Low...Try Again!");
inputNum = Scanner.nextInt();
guesses++;
}
// greater than secretNumber
if (inputNum > secretNumber) {
System.out.println("Too High...Try Again!");
inputNum = Scanner.nextInt();
guesses++;
}
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
Scanner.next();
}
}
System.out.println("\nWell done! The secret number was " + secretNumber + "." + "\nYou took " + guesses + " guesses.");
}
}
Generally, name variable names in java using camelCase in most cases.
You don't actually need to catch any exception in your case as you can simply do scanner.next() if scanner.hasNextInt() is false. Prompting the user to enter specifically a number this time.
Try the below code:
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
class Main {
private static final String GUESS_PROMPT_PATTERN = "Please enter a guess between %d and %d inclusive: ";
private static final String WIN_PROMPT_PATTERN = "Well done! The secret number was %d. You took %d guesses.\n";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minimumGuess = 1, maximumGuess = 100;
int secretNumber = ThreadLocalRandom.current().nextInt(minimumGuess, maximumGuess + 1);
int guesses = 0;
String guessPrompt = String.format(GUESS_PROMPT_PATTERN, minimumGuess, maximumGuess);
System.out.println("Lec's Guessing Game");
System.out.println("====================");
System.out.print(guessPrompt);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
guesses++;
int inputNum = scanner.nextInt();
if (inputNum == secretNumber) {
break;
}
// Input number too high or too low.
if (inputNum > maximumGuess || inputNum < minimumGuess) {
System.out.println("Out of Range!");
scanner.nextLine();
System.out.print(guessPrompt);
}
// Input number was less than the secret number.
else if (inputNum < secretNumber) {
System.out.println("Too Low... Try Again!");
System.out.print(guessPrompt);
}
// Input number was greater than the secret number.
else {
System.out.println("Too High... Try Again!");
System.out.print(guessPrompt);
}
} else {
System.out.print("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
System.out.printf(WIN_PROMPT_PATTERN, secretNumber, guesses);
}
}
So far I have,
package randomnumberguessinggame;
import java.util.Scanner;
public class RandomNumberGuessingGame {
public static void main(String[] args) {
int secretNumber;
secretNumber = (int) (Math.random() * 999 + 1);
Scanner keyboard = new Scanner(System.in);
int guess;
int count = 0;
do {
System.out.print("Enter a guess: (1-1000) ");
guess = keyboard.nextInt();
System.out.println("Your guess is " + guess);
if (guess == secretNumber)
System.out.println("Your guess is correct. Congratulations!");
else if (guess < secretNumber)
System.out.println("Your guess is smaller than the secret number.");
else if (guess > secretNumber)
System.out.println("Your guess is greater than the secret number.");
} while (guess != secretNumber);
}
}
This code works but I need to know how to count the number of user inputs.
Thanks in advance.
Just add count++ under guess = keyboard.nextInt();
Just add one incrementation into your do while loop count = count + 1; as the last command. It would work anywhere in the do loop, but it's logical to put it after the input was processed.
Then add a line System.out.println("Number of guesses:"+count); under your loop.