This is my first time here. I'm starting to learn how to code, so I honestly hope this question I have is not something I can find over here! (I promise I searched for a while, but since I'm a noob in this topic, I didn't found anything understandable for me in order to resolve my doubt).
I'm doing a simple game in JAVA, in which the program generates a random number and the player has to guess the number generated.
When the player enters a number, the game displays a hint, saying if it is higher or lower than the number generated randomly.
The program itself works fine if you enter just numbers, but I want to add a try-catch statement to handle bad user input.
I tried using the statement as I show in my code, but I can't understand why it's not working properly, because when I enter something different of a number, the exception is catched and it prints on console the System.out.println(), but program terminates when this happens.
I would like to try-catch just to get the exception of entering not a number without terminating the program every time the exception is catched.
How can I fix this?
Thanks a lot for your help!
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //Creates Scanner object to read from keyboard
String playAgain = ""; //if == y, game restarts
try {
do {
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
//System.out.println(theNumber); //Uncoment this in case we want to know the number (for testing).
int guess = 0; //Number entered by the player
int count = 0; //Number of tries of guessing the number
while(guess != theNumber){
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt(); //Reads the number typed on the keyboard by the player
count++; //Plus 1 every time a number is entered
System.out.println("You entered " + guess +".");
if(guess < theNumber) { //If number entered is smaller
System.out.println("The number is bigger" + ", try again!");
System.out.println("Number of tries: " + count);
} else if(guess > theNumber) { //If number entered is bigger
System.out.println("The number is smaller" + ", try again!");
System.out.println("Number of tries: " + count);
} else { //If both previous cases are false
System.out.println("Congratulations! You've found the number!");
}
}
//Once guess == theNumber
System.out.println("Number of tries: " + count);
System.out.println("Play again? (y/n)");
playAgain = scan.next(); //Reads the String entered from keyboard by the player
}
while(playAgain.equalsIgnoreCase("y")); //If player enters y, start again.
//Otherwise
System.out.println("Thank you for playing! Goodbye :)");
} catch (Exception e) {
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
}
scan.close(); //Close scanner
} //Close main
} //Close class
place try-catch inside the while loop and reinstantiate the scanner object (scan = new Scanner(System.in) inside the catch block.
while (guess != theNumber) {
try {
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt(); // Reads the number typed on the
// keyboard by the player
count++; // Plus 1 every time a number is entered
System.out.println("You entered " + guess + ".");
if (guess < theNumber) { // If number entered is smaller
System.out.println("The number is bigger" + ", try again!");
System.out.println("Number of tries: " + count);
} else if (guess > theNumber) { // If number entered is
// bigger
System.out.println("The number is smaller" + ", try again!");
System.out.println("Number of tries: " + count);
} else { // If both previous cases are false
System.out.println("Congratulations! You've found the number!");
}
} catch (Exception e) {
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
scan = new Scanner(System.in);
}
}
You need to understand the working of the try-catch block. You don't need to surround the entire code within try. Just put that part of the code which causes an exception. So, in your case just surround guess = scan.nextInt(); with try and then catch an exception. Because, here this statement raises an exception when the input is not an integer. This way you can ensure that the user input is valid for each iteration of the while(guess != theNumber) loop.
Edit_1:
I removed the try-catch blocks from your code and added the following & it works fine for me:
try{
guess = scan.nextInt();} //Reads the number typed on the keyboard by the player
catch (InputMismatchException e){
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
scan.nextLine();
continue;
}
Related
I'm building a dice guessing game. the program has 5 die tosses. I've implemented hasNextInt() as it is the only one I can understand at the moment.
When I enter something that's not an Int it breaks out of the code but I want the program to continue for the rest of the goes (out of 5).
Also If the user guesses correctly I have to keep track of how many they get right.
If they guess wrong I have let them know what the die toss was, this keeps returning the first wrong die toss for the five goes.
At the end I have let the player know how many they got right out of 5.
This is my code so far
import java.util.Scanner;
public class Attempt11
{
public static void main(String args[]) {
int attempt = 1;
int userGuessNumber = 0;
int secretNumber = (int) (Math.random() * 6) + 1;
Scanner userInput = new Scanner(System.in);
System.out.println("Guess the next dice throw (1-6)");
do {
if (userInput.hasNextInt()) {
userGuessNumber = userInput.nextInt();
if (userGuessNumber == secretNumber) {
System.out.println("Congratulations you guessed right");
continue;
} else if (userGuessNumber < 1) {
System.out.println("Number must be between 1 and 6 inclusive, please try again ");
} else if (userGuessNumber > 6) {
System.out.println("Number must be between 1 and 6 inclusive, please try again ");
} else if (userGuessNumber > secretNumber) {
System.out.println("Hard luck the last throw was " + secretNumber);
} else if (userGuessNumber < secretNumber) {
System.out.println("Hard luck the last throw was " + secretNumber);
}
if (attempt == 5) {
System.out.println("You have exceeded the maximum attempt. Try Again");
break;
}
attempt++;
} else {
System.out.println("Enter a Valid Integer Number");
break;
}
} while (userGuessNumber != secretNumber);
userInput.close();
}
}
I'm trying to have my loop only occur three times. So if the user doesn't guess the correct number after their third guess then the loop ends which I have but it doesn't display what the number was. I need the number displayed after the third guess but not sure why it's not displaying the correct number.
import java.util.Scanner;
public class GuessNumberDoWhileA {
public static void main(String[] args) {
//Generate random number from 1-10
int number = (int) (Math.random()*9 + 1);
int count = 0;
//Auto Generated Method stub
Scanner Input = new Scanner(System.in);
//Tell the user to guess a number
System.out.println("Guess a number between 1 and 10");
//int guess = -1;
//while (guess != number) {
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number)
System.out.println("Correct the number was " + number);
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
else
System.out.println("The correct number is " + number);
}
System.out.println("The number was " + number);
}
}
You need a boolean variable that can be used to check whether user was able to guess the number correctly or not. Initial value of this boolean variable should be false.
You don't need the last else statement in the loop. If user guesses the number correctly, set the boolean variable to true and break out of the loop. After the loop, check if the boolean variable is false or not. If it is false, that means user was not able to guess the number, so display the correct number to the user.
If user is able to guess the number then the first if statement in the loop will print the correct number on the console and break out of the loop. It will also set the boolean variable to true, so correct number will be printed only once on the console.
boolean guessed = false;
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number) {
System.out.println("Correct the number was " + number);
guessed = true;
break;
}
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
}
if (!guessed) System.out.println("Number was: " + number);
I'm new to Java programming and taking a college course where I have an assignment to create a Hi/Lo guessing game. The game provides up to 5 attempts for the user to input a number between 1 and 100 (inclusive). The program must provide the logic back of whether the answer is too low, too high or correct. The program must provide the option to play again after either winning or the 5 failed attempts.
I've recreated this program about 10 times :(. I cannot get he logic to work to follow the instructions above. I cannot stop the tries at 5 attempts... and I cannot get the program to execute a new game.
Any help is greatly appreciated. I've spent countless hours writing and re-writing this code with MANY different results - but not the intended ones.
This is my first time posting so, I apologize if the format to post is not correct.
I've looked through more forums and examples than I care to admit and none of code I've reviewed and tried implementing have given me the results of limiting the user input to 5 tries each time and ability to play again multiple times.
Here is my code:
public class HiLoGuessingGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Initialize scanner and random number gennerator
Scanner input = new Scanner(System.in);
Random generator = new Random();
//State the rules of the game
System.out.println("The Hi-Lo Guessing Game. Guess a number between 1-100");
System.out.println("You have 5 attempts!");
/* define the variable Guess (user iput)
define the variable Answer (random generator)
define the variable Counter (track number of tries and limit to 5)
define the variable PlayAgain (Y/N question)*/
int guess = 0;
int answer = generator.nextInt(100)+1;
int counter = 1;
String playAgain;
boolean gameOver = false;
//Ask the Hi-Lo question - pick number 1-100 (inclusive)
//Provide feedback answer too high, too low or you win!
//Limit number of tries in the game to 5
while (guess != answer) {
System.out.print("Enter your guess: ");
guess = input.nextInt();
counter++;
if (guess < answer) {
System.out.println("Your guess " + guess + " is too low. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess > answer) {
System.out.println("Your guess " + guess + " is too high. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess == answer) {
System.out.println("Your guess " + guess + " is correct! You win!");
System.out.println();
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
}
if (counter ==6) {
System.out.println("Sorry, you've reached your max atttempts.");
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
// Play again logic
boolean isValid;
do {
System.out.print("Would you like to play again (Y/N)?");
playAgain = input.next().toUpperCase();
isValid = playAgain.equals("Y") || playAgain.equals("N");
playAgain = input.next();
counter = 1;
if ( !isValid ) {
System.out.println("Error, please enter Y or N");
System.out.println();
}
} while (!isValid);
}
}
You can add an extra condition to your while-loop:
while (guess != answer && counter < 5) {
// ...
}
Alternatively, you can break the loop when you get a right answer:
while (counter < 5) {
// ...
if (answer == guess){
// ...
break;
}
}
I want to give the user a choice to quit the program while the program is running whenever they feel like it. E.g. Press Q and ENTER at anytime to quit and end program.
I have a try and catch method but whenever I press Q and ENTER, it just displays whats in the catch part.
Here is the code:
public static void partB() {
//Code for partB goes here.
//Continues on with partA but with few changes
/* The number of multiplication problems should not be fixed. Instead,
the program should keep posing new multiplication problems until the user decides to quit by entering the letter "q".
The program should be able to deal with invalid input by the user.
It should ignore such input and restate the current multiplication problem.
*/
//Uses the imported Random function.
Random num = new Random();
//Initialises the minimum and maximum numbers.
int minNumber = 10; //Minimum number to start random
int maxNumber = 20; //Maximum number to start random
int counter = 0; //Counts the number of questions answered.
int correctAnswers = 0; //Counts the number of correct answers given.
final int numberOfQuestions = 0;
while(numberOfQuestions >= 0) {
//Generates a random integer between 10 and 20.
int randInt1 = (num.nextInt(maxNumber - minNumber) + minNumber);
//Repeats for the 2nd integer to get the product of the two numbers.
int randInt2 = (num.nextInt(maxNumber - minNumber) + minNumber);
//Initialise the Scanner function.
Scanner input = new Scanner(System.in);
//Output the Question.
System.out.println("What is " + randInt1 + " X " + randInt2 + "?" + " " + "(Press 'q' and ENTER to quit)");
//Waits for user input.
try {
int userInput = input.nextInt();
String quit = input.nextLine();
//If user input is 'q', quit program.
if(quit.equalsIgnoreCase("q")) {
System.out.println("Exiting...");
System.exit(0);
} else {
int answer = randInt1 * randInt2;
//Checks if the users input is correct.
if (answer == userInput) {
System.out.println("That is correct!");
correctAnswers++;
}
else {
System.out.println("That is incorrect! " + "The correct answer should be " + answer);
counter++;
}
}
} catch(InputMismatchException e) {
System.out.println("You have entered something other than an integer or 'q'! Please try again with a different question!");
}
}
}
If you want to accept both a number and a letter, it is better to use nextLine(). First you check for q, and then parse to number, as follows (note that parseInt will throw a NumberFormatException):
try {
String userInput = input.nextLine();
// If user input is 'q', quit program.
if (userInput.equalsIgnoreCase("q")) {
System.out.println("Exiting...");
System.exit(0);
} else {
int userAnswer = Integer.parseInt(userInput);
int answer = randInt1 * randInt2;
// Checks if the users input is correct.
if (answer == userAnswer) {
System.out.println("That is correct!");
correctAnswers++;
} else {
System.out.println("That is incorrect! " + "The correct answer should be " + answer);
counter++;
}
}
} catch (NumberFormatException e) {
System.out.println(
"You have entered something other than an integer or 'q'! Please try again with a different question!");
}
I am writing this guessing game, which enables the user to enter a number as the maximum number.
The random generator will then pick a number between 1 and the max number entered by the user.
It will save and display the number of high guesses and low guesses.
The problem I am having is looping the program and validating.
I can not get the program to loop back after a user has entered the wrong input, i.e. not an integer.
I want it to loop back for another guess after displaying an error message.
I am using a try/catch but after the error message the program does not allow the user to enter another number to continue the game.
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
public class guessinggame { // class name
public static void main(String[] args) { // main method
String smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
int max = Integer.parseInt(smax);
do {
if (max > 10000) {
JOptionPane.showMessageDialog(null, "Oh no! Please keep your number less than 10,000.");
smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
max = Integer.parseInt(smax);
}
} while (max > 10000);
int answer, guess = 0, lowcount = 0, highcount = 0, game;
String sguess;
Random generator = new Random();
answer = generator.nextInt(max) + 1;
ArrayList<String> buttonChoices = new ArrayList<>(); // list of string arrays called buttonChoices
buttonChoices.add("1-" + max + " Guessing Game");
Object[] buttons = buttonChoices.toArray(); // turning the string arrays into objects called buttons
game = JOptionPane.showOptionDialog(null, "Play or Quit?", "Guessing Game",
JOptionPane.PLAIN_MESSAGE, JOptionPane.QUESTION_MESSAGE,
null, buttons, buttonChoices.get(0));
do {
sguess = JOptionPane.showInputDialog("I am thinking of a number between 1 and " + max + ". Have a guess:");
try {
guess = Integer.parseInt(sguess);
} catch (Exception nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
}
if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is too LOW!");
lowcount++;
} else if (guess > answer) {
JOptionPane.showMessageDialog(null, "That is too HIGH!");
highcount++;
}
} while (guess != answer);
JOptionPane.showMessageDialog(null, "Well Done!" + "\n---------------" + "\nThe answer was " + answer + "\nLow Guesses: " + lowcount
+ "\nHigh Guesses: " + highcount + "\n\nOverall you guessed: " + (lowcount + highcount) + " Times");
System.exit(0);
}
}
Ran it on my machine, and it loops back fine. It is broken though; guess is 0 by default, and you continue executing the code after the exception. If it happens that the random number is 0, the program will exit as it's the correct guess. Assuming something like this is happening on your machine?
You also haven't put the protecting logic around the initial "what's your max number" bit.
Use continue; in the try catch.
the code will be like
try {
guess = Integer.parseInt(sguess);
} catch (Exception nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
continue;
}
While I can't see the problem you are describing, may I suggest that you put the comparison code inside the try block, so that you can be sure the guess variable will be set properly before doing any comparison:
try {
guess = Integer.parseInt(sguess);
if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is too LOW!");
lowcount++;
} else if (guess > answer) {
JOptionPane.showMessageDialog(null, "That is too HIGH!");
highcount++;
}
} catch (Exception nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
}