So I am working on a guessing number game that uses a try/catch block to catch (this is homework). If the user enters a non-integer value or a number that is below or above the given range (in this case 1-10).
But I am having issues understanding/properly placing the try catch block I read on how it works but when I try to implement it into my simple code it just seems to be ignored.
Here is the code
//import statements
import java.util.*; //for scanner class
// class beginning
class Guess {
public static void main(String[] args ) {
//Declare variables area
int secretNumber, guess;
secretNumber = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
// beginning message to user to explain the program
System.out.println("Welcome to my guess a number program!");
System.out.println("Please enter in a number to begin guess what the secret number is(1-10): ");
//Collect inputs from user or read in data here
System.out.println("Enter a guess (1-10): ");
try {
guess = keyboard.nextInt();
if (guess < 1 || guess > 10){
}
} catch (InputMismatchException e) {
guess= keyboard.nextInt();
System.out.println("Not a valid integer");
}
//Echo input values back to user here
//main code and calculations to do
do {
if (guess < 1 || guess > 10) {
System.out.println("Your guess is not in the corre try again.");
guess = keyboard.nextInt();
}
if (guess == secretNumber) {
System.out.println("Your guess is correct. Congratulations!");
guess = keyboard.nextInt();
} else if (guess < secretNumber) {
System.out
.println("Your guess is smaller than the secret number.");
guess = keyboard.nextInt();
} else if (guess > secretNumber) {
System.out
.println("Your guess is greater than the secret number.");
guess = keyboard.nextInt();
}
} while (guess != secretNumber);
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
It doesn't display "Your guess is correct. Congratulations!" when you guess the right number.
Am I implementing the try catch block correctly? If not how do I and can it be explained so I can do the second one where it catches the float, string and anything not a int.
what it does do
it correctly randomizes from 1-10
the program does check to see if it is within the given range
EDIT
below is the updated code my only issue I have with it now is that I can't figure out how to apply another catch if a user just hits enter without entering anything I assume I'd need to take the input from user turn it into a string then compare?
//import statements
import java.util.*; //for scanner class
// class beginning
public class Guess {
public static void main(String[] args ) {
//Declare variables area
int guess, secretNumber = (int) (Math.random() * 10 + 1), lowGuess,highGuess;
Scanner keyboard = new Scanner(System.in);
// beginning message to user to explain the program
System.out.println("Welcome to my guessing number program!");
System.out.println("Please enter in a number to start guessing(enter in a number between 1-10): ");
//main code and calculations to do
guess = 0;
lowGuess = 0;
highGuess = 11;
do {
try {
guess = keyboard.nextInt();
if (guess < 1 || guess >10){
System.out.println("Your guess is not in the correct range try again.");
}
else if(guess == secretNumber){
System.out.println("Your guess is correct. Congratulations!");
}
else if(guess < secretNumber && guess <= lowGuess){
System.out.println("The number you entered is either the same entered or lower please re-enter");
}
else if (guess < secretNumber && guess > lowGuess){
lowGuess = guess;
System.out.println("Your guess is smaller than the secret number.");
}
else if ( guess > secretNumber && guess >= highGuess ){
System.out.println("The number you entered is either the same entered or higher please re-enter");
}
else if (guess > secretNumber && guess < highGuess){
highGuess = guess;
System.out.println("Your guess is greater than the secret number.");
}
} catch (InputMismatchException e) {
System.out.println("Not a valid input please re-enter");
keyboard.next();
guess = 0;
}
} while (guess != secretNumber);
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
What do you want to do here ?
if (guess < 1 || guess > 10) {
}
You should try something like this :
public class Guess {
static int guess, secretNumber = (int) (Math.random() * 10 + 1);
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args ) {
do {
try {
guess = keyboard.nextInt();
if (guess < 1 || guess >10){
System.out.println("Your guess is not in the corre try again.");
}
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.");
}
} catch (InputMismatchException e) {
System.out.println("Not a valid integer");
}
} while (guess != secretNumber);
}
}
EDIT : You have to put a piece of code which could maybe throw an exception, in the scope of the try block. It is state of the art to know which part of the code to put in the try block (not too much nor too less).
in-between the try and catch you have your main code/calculations to
do and then you close it off and end with the catch to see if after
all that if what was entered was valid?
You could always catch the exceptions at top level like you're saying here, but in practice that's not the way to do it. Because when an exception occurs and you don't catch it there will be a process called stack unwinding.
It's really important to understand how stack unwinding works in order to understand what's happening.
You can find information about how this process works here : Explanation of stack unwinding. It explains stack unwinding in C++ but I expect it to be (exactly) the same in Java.
This is another approach, but using Exceptions. Please, read this page to understand how try/catch block works.
//import statements
import java.util.*; //for scanner class
// class beginning
class Guess {
public static void main(String[] args ) {
//Declare variables area
int secretNumber, guess;
secretNumber = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
// beginning message to user to explain the program
System.out.println("Welcome to my guess a number program!");
System.out.println("Please enter in a number to begin guess what the secret number is(1-10): ");
//Collect inputs from user or read in data here
//main code and calculations to do
do {
System.out.println("Enter a guess (1-10): ");
try {
guess = keyboard.nextInt();
if (guess < 1 || guess > 10){
throw new Exception("Number must be between 1 and 10");
}else if(guess == secretNumber){
throw new Exception("YOU WIN");
}
else if (guess < secretNumber){
throw new Exception("NUMBER IS +");
}
else if (guess > secretNumber){
throw new Exception("NUMBER IS -");
}
} catch (InputMismatchException e)
{
System.println("mustbeanumber");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
} while (guess != secretNumber);
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class`
Related
I am still new to Java and as such I am still figuring some things out. I have been having issues with including code asking the user if they want to play again. I have attempted putting it in the main class in a print statement which gave me an error. After that, I attempted putting it in the Guess.java class in multpile places but I just recieved errors. I have read up on the issue and some sites have suggested a while loop but I am unsure how to implement it into my current code. I have included both the main class which is called GuessingGame.java and the Guess.java class below. Thank you for any assistance that can be provided.
GuessingGame.java
public class GuessingGame {
public static void main(String[] args) {
new Guess().doGuess();
}
}
Guess.java
class Guess {
private int answer = 0;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess, i;
boolean win = false;
int amount = 10;
public Guess() {
answer = generateRandomNumber();
}
//Generate a private number between 1 and a thousand
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(1000) + 1;
}
public void doGuess() {
while (!win) {
System.out.println("You are limited to ten attempts."
+ " Guess a number between 1 and 1000: ");
guess = input.nextInt();
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number"
+ " was: " + answer);
System.out.println("Do you want to play again?: ");
return;
}
if (guess > 1000) {
System.out.println("Your guess is out of the range!");
} else if (guess < 1) {
System.out.println("Your guess is out of the range!");
} else if (guess == answer) {
win = true;
tries++;
} else if (guess < answer && i != amount - 1) {
System.out.println("Your guess is too low!");
tries++;
} else if (guess > answer && i != amount - 1) {
System.out.println("Your guess is too high!");
tries++;
}
}
System.out.println("Congragulations! You guessed the number!"
+ "The number was: " + answer);
System.out.println("It took you " + tries + " tries");
}
}
You already found a good position for adding this functionality:
System.out.println("Do you want to play again?: ");
The first step now is to also tell the user what he/she should enter after that question:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
After that we need to get the user input of course:
int number;
//If the user enters e.g. a string instead of a number, the InputMismatchException
//will be thrown and the catch-block will be executed
try {
number = input.nextInt();
//If number < 0 OR number > 1
if(number < 0 || number > 1) {
//The rest of the try-block will not be executed.
//Instead, the following catch-block will be executed.
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
//Clears the scanner to wait for the next number
//This is needed if the user enters a string instead of a number
input.nextLine();
}
If you don't know about try-catch-statements yet, I suggest to read this explanation. For details about the InputMismatchException, please see the documentation.
The problem now is that the user only has one chance to enter 0 or 1. If the user makes a wrong input the program will just stop. One solution to this problem is to just put the code in a while-loop:
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
After this block, we can be sure that number is either 0 or 1. So now we can add a simple if-statement to check the value:
if(number == 0) {
new Guess().doGuess();
}
return;
So all in all the code looks like this:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
if(number == 0) {
new Guess().doGuess();
}
return;
Don't forget to add the following import-statements:
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
Try this. Basically, if the user responds with "yes" , we will call the function again.
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number" + " was: " + answer);
System.out.println("Do you want to play again? (yes/no): "); // modified line
if("yes".equalsIgnoreCase(input.next())){ // newly added if block
answer = generateRandomNumber();
tries=0;
i=0;
win = false;
doGuess();
}
return;
}
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.");
}
}
}
}
Create a program that randomly generates a number from 1-100 and asks the user to guess it. If the number the user inputs is to low or to high display a message to tell them so. When the user guesses the random number tell the user how much tries it took him to get that number. After that ask the user if they want to do it again if the user does repeat the process with a new random number generated.
The problem is that I can't seem to figure out how to let the user do it again, it seems to display an error in code when I run the program. If anyone can help me with this issue that would be great. Thank you!
import java.util.Scanner;
import java.util.Random;
public class RandomGuess
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
Random randy = new Random();
//#declaring variables
int num, count = 0;
final int random = randy.nextInt(100);
String input;
char yn;
//#random number
System.out.println("Num = " + random);
//#title or header
System.out.println("Random Number Guessing Game");
System.out.println("===========================");
//#asking user for input
do
{
System.out.print("Guess the random number " +
"from 1 to 100===> ");
num = keyboard.nextInt();
//#if the number the user entered
//#was less than the random number
if(num < random)
{
//#display this message
System.out.println("Your guess is too low try again...");
System.out.println();
}
//#if the number the user entered
//#was less than the random number
if(num > random)
{
//#display this message
System.out.println("Your guess is too high try again...");
System.out.println();
}
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
}
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y');
}
while (num > 1 || num > 100);
}
}
There are a couple of problems with your code without even seeing the error that is displayed (I've put comments in those areas):
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
} // You should put an else here
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y'); // This will keep asking if you want to try again so long as you enter a "y"
// But it won't actually let you try.
// Why? Because if you enter a y" it will loop back to the question.
}
while (num > 1 || num > 100); // This should probably be (random != num)
}
}
Here is a revised version
count++;
if (num == random) {
System.out.println("You guessed the random number in " +
count + " guesses!");
} else {
yn = 'x'; // can be anything other than y or n
while(yn != 'y' && yn != 'n') {
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.toLowerCase().charAt(0);
}
}
}
while (num != random && yn == 'y');
}
}
Hopefully this is enough to move you forward.
Also, please post the error message and/or a description of what it is doing wrong along with a description as to what you actually wnt it to do.
As for the exception, the problem is that scanner.nextInt does not consume the newline at the end of the numbe you entered. So, your "continue Y/N" question gets what's left over from the previous line (i.e. a new line => an empty string).
You could try this:
num = -1; // Initialise the number to enable the loop
while (num <= 1 || num >= 100) {
System.out.print("Guess the random number from 1 to 100===> ");
String ans = keyboard.nextline();
try {
num = Integer.parseInt(); // Convert the string to an integer - if possible
} catch (NumberFormatException e) {
// If the user's input can not be converted to an integer, we will end up here and display an error message.
System.out.println ("Please enter an integer");
}
}
I have two questions regarding my code.
Why does is the output "Oops please enter a number between 1 and 6" when I enter a number between 1 and 6. When I try to be more specific and make an else if statement, nothing happens when I enter a number NOT between 1 and 6.
How do I restart my program? In my code, there is an if statement
when the user inputs "play again" My commented out line reads
Mastermind.main() to re run the program, but that didn't work.
Here is the code:
import java.util.Scanner;
public class Mastermind {
public static void main (String [] args) {
// boolean variable to signal when the game is over.
boolean done = false;
// Scanner object
Scanner scanner = new Scanner(System.in);
// sets the value to twelve outside the loop so it doesn't set back each time.
int guesses = 12;
System.out.println("Please enter a number between 1-6 to begin (or \"quit\") to exit.");
// while loop for the game
while (!done) {
//System.out.println("Please enter a number between 1-6 (or \"quit\") to exit the game:");
// user input
String input = scanner.nextLine();
int number = 0; //Just initialized to some number
// checks to see if the user wants to quit the game.
if (input.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else{
try{
//Trying to see if the input was a number
number = Integer.parseInt(input);
}
catch(Exception e){
//The input wasn't an integer, it's invalid the starts loop again.
System.out.println("Invalid input.");
continue;
}
}
// defines necessary int variables
int random1 = (int) (Math.random() * 7);
int random2 = (int) (Math.random() * 7);
int random3 = (int) (Math.random() * 7);
int random4 = (int) (Math.random() * 7);
// If the user doesn't and decides to play, it runs this code.
// checks to see if the user enters a number between 1-6
if (number >= 1 && number <= 6) {
if (number == random1) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random2) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random3) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random4) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else {
System.out.println("Sorry that's not one of the numbers! Try again.");
guesses--;
System.out.println("guesses = " + guesses);
}
}
if (guesses == 0){
System.out.println("You've run out of guesses. To play again, enter \"play again\". Otherwise, enter or \"quit\")");
if (input.equalsIgnoreCase("play again")){
// how do I restart the program?
//Mastermind.main(); // QUESTION 2
}
else if (input.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
}
}
}
You're printing that message every time through the loop whenever guesses == 0 evaluates to false. You probably just need to switch the order of the two blocks. Instead of this:
if (number >= 1 && number <= 6) {
...
}
if (guesses == 0) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
Use this:
if (number >= 1 && number <= 6) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
if (guesses == 0) {
...
}
Regarding restarting your program: if I'm reading the logic correctly, all you need to do is keep done set to false and reset guesses to 12.
Two other logic points. First, you should probably either continue or break after detecting that the user has entered "quit". Second, it seems like you are generating four new random integers for every user guess. I don't know if that's what you intended, but you might want to change the logic a bit. That might also affect the restart logic.
I have a quick question about this HiLo game that I have been trying to fix from a while now. When I run the program it counts guesses outside of the 0-10 range, but I don't want it to do that. How do I fix that? Here is my code.
import java.util.Random; // Random number generator class
import java.util.Scanner; // reads user inputs
public class HiLo
{
public static void main(String[] args)
{
// declare variables
final int MAX = 10;
int answer, guess;
int numberOfTries = 0;
String again;
Scanner Keyboard = new Scanner(System.in);
do
{
System.out.print(" I'm thinking of a number between 0 and "
+ MAX + ". Guess what it is: ");
guess = Keyboard.nextInt();
// guess
Random generator = new Random(); // Random number generator. 0 to 10.
answer = generator.nextInt(MAX) + 1;
if (guess > 10) // if guess is bigger than 10 then error message
{
System.out.println("ERROR – Your guess is out of the range 0 to 10.");
}
if (guess < 0) // if guess is smaller than 0 then error message
{
System.out.println("ERROR – Your guess is out of the range 0 to 10.");
}
while (guess != answer) // If guess is not the answer
{
if (guess > answer) // If guess is more than the answer
{
System.out.println("You guessed too high! \nTry again:");
guess = Keyboard.nextInt();
}
if (guess < answer)// If guess is less than the answer
{
System.out.println("Too Low! \nTry again:");
guess = Keyboard.nextInt();
}
numberOfTries = numberOfTries + 1;
}// end of the loop
// display result
if (guess == answer)
{
numberOfTries += 1;
System.out.println("YOU WIN!");
System.out.println("It took you " + numberOfTries + " tries!");
System.out.println();
System.out.print("Do you want to play again(Y/N)?");
}
Keyboard.nextLine(); // skip over enter key
again = Keyboard.nextLine();
numberOfTries = 0;
} while (again.equalsIgnoreCase("Y"));
} // end of class
} // end of main
You report the error but you don't continue; (and use a logical ||) like this
if (guess < 0 || guess > 10) {
System.out.println ("ERROR – Your guess is out of the range 0 to 10.");
again = "Y"; // <-- make sure we'll re-evaluate.
continue; // <-- Add then skip the rest of the loop body
}