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.");
}
}
}
}
Related
I am new to coding. I created a guessing game, and it works well but, I would like to know how to make it so that after the user attempts guessing the number 3 times, they get a hint which I put on the last line, but it is currently unreachable, and I do not know how to make the statement reachable, and in the do while loop. I am currently stuck. Thank you
import java.util.Scanner;
public class guessing_game {
public static void main (String[] args) {
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc() {
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
public static int run(Scanner kb) {
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
int num = 44;
int tries = 0;
do {
if (guess < num) {
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
run(kb);
}
else if ((guess > 100) || (guess < 0)) {
System.out.println("That isn't between 1-100 is it?");
System.out.println();
run(kb);
}
else if (guess > num) {
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
run(kb);
}
else if(guess == num) {
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y")) {
run(kb);
}
else if (choice.equalsIgnoreCase("n")) {
System.exit(0);
}
}
tries++;
}while(tries < 3);
{
System.out.print("Here's a hint the lucky number is 4");
}
return guess;
}
}
There are a few flow issues with your program, but here is a simple way to fix it up.
First of all, you are not actually using the value of guess when you return it from your run() method, so that can be removed.
Also, in cases like this, you would not want to use a do/while loop, but just while. You want to keep repeating the prompt until the user guesses correctly. So add a boolean to allow you to check if they won:
boolean correct = false; - We set it false to begin because they haven't won yet.
Now, instead of calling run() again after every guess (which resets the tries count every time, just let the while loop do its job and repeat itself. Hence, we need to move the prompt input into the while loop.
Here is a complete code listing of the changes:
import java.util.Scanner;
public class guessing_game {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc() {
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
// Change the return type to void as you never use the value returned
public static void run(Scanner kb) {
int num = 44;
// Add a boolean to determine if the game is won
boolean correct = false;
int tries = 0;
while (!correct) {
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
if (guess < num) {
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
} else if ((guess > 100) || (guess < 0)) {
System.out.println("That isn't between 1-100 is it?");
System.out.println();
} else if (guess > num) {
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
} else if (guess == num) {
// Flag the guess as correct; this will exit the loop after this run
correct = true;
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y")) {
run(kb);
} else if (choice.equalsIgnoreCase("n")) {
System.exit(0);
}
}
tries++;
}
}
}
1.You are recursively calling run() method and every time you call this method, a new variable try will be created and initialised to zero.
2. Your recursive call is before the condition check and due to the same reason the logic may never reach the condition check.
To make this work with minimal changes, you can use the following code. But this is not the best as it does not resolve the above shortcomings
import java.util.Scanner;
public class guessing_game {
static int tries = 0;
public static void main (String[] args)
{
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc()
{
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
public static int run(Scanner kb)
{
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
int num = 44;
do{
tries++;
if(tries>=3) break;
if (guess < num)
{
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
run(kb);
}
else if ((guess > 100) || (guess < 0))
{
System.out.println("That isn't between 1-100 is it?");
System.out.println();
run(kb);
}
else if (guess > num)
{
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
run(kb);
}
else if(guess == num)
{
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y"))
{
run(kb);
}
else if (choice.equalsIgnoreCase("n"))
{
System.exit(0);
}
}
}while( tries < 3);
{
System.out.print("Here's a hint the lucky number is 4");
}
return guess;
}
}
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.
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);
}
}
How would I make my game have multiple lives until I can finally get the correct number?
import java.util.Scanner;
public class GuessNumberOneTime {
public static void main(String[] args) {
// Generate a random number to be guessed
int number = (int)(Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Guess a magic number between 0 and 100");
// Prompt the user to guess the number
System.out.print("\nEnter your guess: ");
int guess = input.nextInt();
if (guess == number)
System.out.println("Yes, the number is " + number);
else if (guess > number)
System.out.println("Your guess is too high");
else
System.out.println("Your guess is too low");
}
In order for your program to have multiple lives initialize a variable called guess and then run the int number through a while loop until the correct number has been chosen! Here’s an example of what you could do:
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
// Generate a random number to be guessed
int number = (int)(Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Guess a magic number between 0 and 100");
int guess = -1;
while (guess != number) {
// Prompt the user to guess the number
System.out.print("\nEnter your guess: ");
guess = input.nextInt();
if (guess == number)
System.out.println("Yes, the number is " + number);
else if (guess > number)
System.out.println("Your guess is too high");
else
System.out.println("Your guess is too low");
} // End of loop
}
}
import java.util.Random;
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
System.out.println("Guess a number betwwen 1 and 1000");
Random rand = new Random();
int secretNumber = rand.nextInt (1000);
Scanner keyboard = new Scanner(System.in);
int guess;
do {
guess = keyboard.nextInt();
if (guess == secretNumber)
System.out.println("You WON!!! Congratulations!");
else if (guess < secretNumber)
System.out.println("Nope, to low");
else if (guess > secretNumber)
System.out.println("Sorry, to high");
} while (guess != secretNumber);
}
}
how can i add to this code a statement, that IF NOT NUMERIC INPUT System.out.println("invalid input, please use type numbers only!")
You should use Scanner's hasNextInt() method to determine if the input is numeric before calling nextInt:
do {
while (!keyboard.hasNextInt()) {
System.out.println("Please enter only numbers.");
keyboard.next(); // Skip the wrong token
}
// Now that the input is valid, read the value:
guess = keyboard.nextInt();
// Put the rest of your logic here
...
} while (guess != secretNumber);
Scanner.nextInt() throws
InputMismatchException if the next token does not match the Integer regular expression, or is out of range
So you should wrap your code around a try-catch with this in mind
I think you want the following wrapped around guess = keyboard.nextInt():
try
{
guess = keyboard.nextInt()
Integer.parseInt(guess);
<your if statements>
} catch(Exception ex)
{
System.out.println("Your comment");
}
You can add a try catch block inside your loop.
do {
try{
guess = keyboard.nextInt();
if (guess == secretNumber)
System.out.println("You WON!!! Congratulations!");
else if (guess < secretNumber)
System.out.println("Nope, to low");
else if (guess > secretNumber)
System.out.println("Sorry, to high");
}
catch(InputMismatchException e){
System.out.prinln("Not a number");
}
} while (guess != secretNumber);
While using a scanner you will never figure out if it is an integer that has been entered or not. It will just wait until the "nextInt" is entered. What you can do is use the
Integer.parseInt() method. It will throw a NumberFormatException if the input string is not an integer.
Make guess a string and use. guess = keyboard.next();
Then use Integer.parseInt(guess) in a try-catch to solve your problem.
public class Game {
public static void main(String[] args) {
System.out.println("Guess a number betwwen 1 and 1000");
Random rand = new Random();
int secretNumber = rand.nextInt (1000);
Scanner keyboard = new Scanner(System.in);
int guess;
do {
if (!keyboard.hasNextInt()) {
System.out.println("invalid input, please use type numbers only!");
return;
}
guess = keyboard.nextInt();
if (guess == secretNumber)
System.out.println("You WON!!! Congratulations!");
else if (guess < secretNumber)
System.out.println("Nope, to low");
else if (guess > secretNumber)
System.out.println("Sorry, to high");
} while (guess != secretNumber);
}
}
import java.util.Random;
import java.util.Scanner;
public class Game {
public static boolean isInteger( String input )
{
try
{
Integer.parseInt( input );
return true;
}
catch( Exception e)
{
return false;
}
}
public static void main(String[] args) {
System.out.println("Guess a number betwwen 1 and 1000");
Random rand = new Random();
int secretNumber = rand.nextInt (1000);
Scanner keyboard = new Scanner(System.in);
int guess=-1;
do {
String g = keyboard.next();
if(isInteger(g)){
guess = Integer.parseInt(g);
if (guess == secretNumber)
System.out.println("You WON!!! Congratulations!");
else if (guess < secretNumber)
System.out.println("Nope, to low");
else if (guess > secretNumber)
System.out.println("Sorry, to high");
}
else{
System.out.println("NaN");
}
} while (guess != secretNumber);
}
}