I'm writing a simple game that asks a user to type in an integer. If they type in anything else I want to tell them it was invalid and have them try again. I am using eclipse and it seems like no matter what I try when the user(me) puts in an invalid entry my program stops.
I have even tried to use the "finally" method after the catch because everyone says the code will run but it does not. I have tried to use a loop but that is not working either. any ideas or reasons? keep in mind I am brand new to Java and I'm on my second project in the microsoft course so there is a lot i do not understand.
I am assuming I need to write the solution in the catch area but I dont know.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Play {
public Play() {
Scanner input = new Scanner(System.in);
try {
System.out.println("Choose how many fingers you wish to play.");
input.nextInt();
if(input.nextInt() < 0 || input.nextInt() > 10) {
System.out.println("That is not a valid number. Please enter a number between 1 and 10.");
input.nextInt();
}else if(input.nextInt() > 0 && input.nextInt() < 11) {
System.out.println("Great, you chose "+input.nextInt()+" fingers.");
}
}catch(InputMismatchException notInt) {
System.out.println("That was not a number!");
}
}
}
You're not assigning input.nextInt() to a variable.
import java.util.InputMismatchException;
import java.util.Scanner;
class Play {
public Play() {
Scanner input = new Scanner(System.in);
try {
System.out.println("Choose how many fingers you wish to play.");
int n = input.nextInt();
if (n > 0 && n < 11) System.out.println("Great, you chose " + n + " fingers.");
else System.out.println("That is not a valid number. Please enter a number between 1 and 10.");
} catch (InputMismatchException notInt) {
System.out.println("That was not a number!");
}
}
}
Related
I am needing to stop the user from entering a string value.
Here is what I've tried so far.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Random;
public class guessinggame
{
public static void main (String[] args)
{
int randomNumber = new Random().nextInt(10);
System.out.println("My number is " + randomNumber + ". ");
System.out.println("I’m thinking of a number between 0 and 9.");
System.out.println("What is your guess:");
Scanner keyboard = new Scanner(System.in);
int guess = keyboard.nextInt();
guess1(guess);
int input = 0;
try{
input = keyboard.nextInt();
}catch (InputMismatchException e){
int guess = keyboard.nextInt();
System.out.println("Invalid.");
}
if (guess < randomNumber) {
System.out.print("your guess was too low.");
}else if (guess > randomNumber){
System.out.print("your guess was too high.");
}else if (guess == randomNumber){
System.out.print("your guess was correct.");
}
}
}
The error I am receiving is: Duplicate local variable guess preventing program from compiling, however I imagine I am also missing bits from making this program do what I want it to.
It needs to only accept integer values as input between 0-9. Anything else (including strings) should return as invalid.
The compiler is giving you the error because you have declared guess twice:
Once at the beginning with int guess = keyboard.nextInt();
Then in the catch clause with int guess = keyboard.nextInt(); again
Also note that you readInt() several times in your code, meaning that you are trying to get user input several times. You should reference guess in your code instead.
If you are often having trouble with compile errors and such, you may want to use an IDE such as Eclipse.
The main error is that you are re-declaring guess in the catch block.
What you really need to do is loop around if invalid data is input
int guess = -1; // some magic number
while (guess <= -1) { // we do not want negative number
try{
guess = keyboard.nextInt();
}catch (InputMismatchException e){
System.out.println("Invalid - try again.");
continue;
}
if (guess >= 0) {
break;
}
System.out.println("We want between 0 and 9 - try again.");
}
// now we have valid value for guess
Edit
As per new requirements
int guess = -1; // some magic number
try{
guess = keyboard.nextInt();
}catch (InputMismatchException e){
// do not need to do anything
}
if (guess < 0) {
System.out.println("Invalid - will exit.");
System.exit(-1);
}
// now we have valid value for guess
int guess = keyboard.nextInt();
should just be
guess = keyboard.nextInt();
I am trying to create a custom exception class and I'm having a lot of trouble. Can someone help me out! I just started programming very recently and i'm hoping to get some pointers.
import java.util.Random;
import java.util.Scanner;
import java.util.InputMismatchException;
public class GuessingGame {
public static void main(String[]args) throws BadGuessException
{
int min = 1;
int max = 10;
Random rand = new Random();
int numberToGuess = rand.nextInt((max - min) + 1) + min;
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
int numberOfTries = 0;
while (!win)
{
System.out.println("Guess a number between 1 and 10: ");
try
{
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess)
{
win = true;
System.out.println("YOU GOT IT!");
System.out.println("It took you " + numberOfTries + " tires.");
}
else
{
throw new BadGuessException();
}
}
catch(InputMismatchException e)
{
e.getMessage();
}
}
}
}
import java.util.*;
public class BadGuessException extends Exception {
String message = "Sorry, that was an invalid guess!";
//Default Constructor
public BadGuessException()
{
super();
}
//Parameterized Constructor
public BadGuessException(Throwable cause)
{
super(cause);
}
}
I'm supposed to create 2 constructors, one default and one parametrized. If the user enters a number between 1-10, i should catch it in a catch block and print the message "invalid guess" And if they enter a letter or something, the output should be something like "Invalid input" ( Should I catch invalid input in BadGuessException and then pass it to InputMismmatch? If so, how do I do that?)
Right now, when I run this code, if I enter a letter, it doesn't crash, but the while loop iterates continuously and I'm not able to enter anymore inputs. It just keeps repeating "Guess a number between 1-10."
I'm assuming it's because once the try block executes once, it doesn't execute again? How do I fix this? Sorry for any confusion, happy to clarify! any help is much appreciated.
Also, I'm not sure how to catch 2 different exceptions at the same time. One for invalid guess and one for invalid input. :/
Exceptions should be used for handling errors, invalid input, illegal, unusual situations. If not guessing the correct number is an error, that sounds like not being a mind reader is an error. So BadGuessException is misused here.
For a better use case, how about throwing this exception for non-sense input? For example, since the program asks the user to input a number between 1 and 10, inputting -3 or 99 would be clearly an error.
The loop in the middle can be corrected accordingly:
while (!win) {
System.out.println("Guess a number between 1 and 10: ");
try {
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
System.out.println("YOU GOT IT!");
System.out.println("It took you " + numberOfTries + " tires.");
} else if (guess < 1 || guess > 10) {
throw new BadGuessException();
}
} catch (InputMismatchException e) {
input.nextLine();
}
}
As for creating a custom exception class, you already did that. It's written a bit messy way, cleaning it up (removing unnecessary stuff) it becomes:
public class BadGuessException extends Exception {
private static final String message = "Sorry, that was an invalid guess!";
public BadGuessException() {
super(message);
}
}
UPDATE
I fixed another bug in your code: if you enter non-integer input, a InputMismatchException will be thrown. Repeatedly. Forever.
This is because the input.nextInt() doesn't consume the input if it's not valid. So the invalid input stays there, and input.nextInt() will keep failing, putting your program in an infinite loop.
To fix that, you must consume the bad input somehow, for example by reading the line:
} catch (InputMismatchException e) {
input.nextLine();
}
I think what you want is if they make a guess and it is incorrect, that your loop should run again, right? In that case, you should adjust your loop, as I've shown below. Also, where you are catching the InputMismatchException, you are swallowing the exception without printing it or handling it: This is VERY BAD PRACTICE. I've updated this too for you.
while (!win)
{
System.out.println("Guess a number between 1 and 10: ");
try
{
guess = input.nextInt();
numberOfTries++;
win=true;
if (guess == numberToGuess)
{
win = true;
System.out.println("YOU GOT IT!");
System.out.println("It took you " + numberOfTries + " tires.");
}
else
{
throw new BadGuessException();
}
}
catch(InputMismatchException e)
{
System.out.println("Please input a number betwee 1 and 10!");
}
catch(BadGuessException ex) {
System.out.println("Sorry, you guessed the wrong number!");
}
}
You never catch the BadGuessException so it will be thrown out of the while loop and program will exit. You must catch the exception inside the loop if you want to continue.
I agree with janos comment that this is not a good use of exceptions. Guessing wrong is part of the normal game flow, no?
But doing it for the practice, I'd for example pull all logic inside the loop into a new private method, let it throw this exception, and catch it in the loop. You can catch multiple exceptions in a row like this.
while (!win) {
try {
win = makeGuess();
} catch (InputMismatchException e) {
e.getMessage();
} catch (BadGuessException e) {
System.out.println("Wrong guess");
}
}
private boolean makeGuess() throws BadGuessException, InputMismatchException {
...
}
This is currently my code.
What I want it to do, is accept up to 10 numbers in an array then do and display some math for them. What I managed to do, is catch errors, then stop the program.
What I want it to do, is keep the program running until the user correctly enters an integer.
I managed to do something similar for my y/n string, but I don't know how to do it for integer arrays.
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int i=0, numberlist[] = new int [10];
String yn=null;
while (i < 10)
{
try {
System.out.print("Please enter your number\n");
numberlist[i]=input.nextInt();
System.out.print("Would you like to enter another number? (y/n)\n");
yn=input.next();
i++;
if (i==10)
{System.out.println("You reached the maximum amount of numbers\n");
break;}
if (yn.equals("n"))
break;
else if (!yn.equals("y"))
while (true)
{System.out.print("Please only enter a 'y' for yes or 'n' for no next time.\nDo you understand? Type 'y' to continue\n");
yn=input.next();
if (yn.equals("y"))
break;
}
}catch (Exception e){System.out.println("Please enter the correct number(integers only) next time.");}
}
int max=numberlist[0], min=numberlist[0], numlength = i, sum=0;
float average;
for(i = 0; i < numlength; i++) {
if(numberlist[i] > max)
max = numberlist[i];
}
for(i = 0; i < numlength; i++) {
if(numberlist[i] < min)
min = numberlist[i];
}
for(i = 0; i < numlength; i++) {
sum=numberlist[i]+sum;
}
average = (float)sum/(float)numlength;
System.out.println("Your Sum is: "+sum);
System.out.println("Your Average is: "+average);
System.out.println("Your Maximum is: "+max);
System.out.println("Your Minimum is: "+min);
}
Move your error handling for numbers inside the while loop so that any exceptions don't break the flow out of the loop and end the program.
while (i < 10) {
try {
System.out.print("Please enter your number\n");
numberlist[i] = input.nextInt();
System.out.print("Would you like to enter another number? (y/n)\n");
yn = input.next();
i++;
if (i == 10) {
System.out.println("You reached the maximum amount of numbers\n");
break;
}
if (yn.equals("n"))
break;
else if (!yn.equals("y"))
makeUserUnderstand(input,
"Please only enter a 'y' for yes or 'n' for no next time.");
} catch (InputMismatchException e) {
makeUserUnderstand(input,
"Please enter the correct number (integers only) next time.");
}
}
I've moved out the common "Do you understand?" part into a method.
private static void makeUserUnderstand(Scanner input, String msg) {
while (true) {
System.out.println(msg);
System.out.println("Do you understand? Type 'y' to continue\n");
if (input.next().equals("y"))
break;
}
}
First of all, don't catch Exception. You should catch only the specific exceptions that you care about and know might occur in your code. Any other exceptions indicate a serious problem and by catching them, you can accidentally squelch important information that indicates a bug that needs your attention.
With that said, you can solve your problem by making your try block smaller by only wrapping the code that reads input. In addition, create a loop that checks a flag that indicates if an error occurred. The flag can be set in the catch block when an error occurs parsing the input into an integer.
If you have trouble translating my description into code, feel free to ask about the details.
In the below code, I ask the user to give an integer input and if the input is 0 or a negative number, it loops again until the positive number is given. The thing is that if the users presses a letter, my code crashes and despite the fact that I used try-catch in a lot of ways nothing really worked. Any ideas?
I used try-catch inside the loop, but it only worked for one letter input and not correctly.
System.out.print("Enter the number of people: ");
numberOfPeople = input.nextInt();
while (numberOfPeople <= 0) {
System.out.print("Wrong input! Enter the number of people again: ");
numberOfPeople = input.nextInt();
}
The problem in your current code is that you're always trying to read an int so when receiving a non-integer input you can't handle the error in the right way. Modify this to always read a String and convert it into an int:
int numberOfPeople = 0;
while (numberOfPeople <= 0) {
try {
System.out.print("Enter the number of people: ");
numberOfPeople = Integer.parseInt(input.nextLine());
} catch (Exception e) {
System.out.print("Wrong input!");
numberOfPeople = 0;
}
}
//continue with your life...
I have this small snippet of coding that requires an input from the user when it is ran to determine a certain value. I don't want the user to be able to enter anything less than 0 and anything greater than 1 million, so, 0 =< YEARS_AHEAD =< 1000000.
I've looked through so many tutorials and searched for help on this and found nothing. This is my code.
Scanner reader = new Scanner(System.in);
int YEARS_AHEAD;
System.out.print("Enter the amount of years ahead: ");
while (true)
try {
YEARS_AHEAD = Integer.parseInt(reader.nextLine());
break;
}catch (NumberFormatException nfe) {
System.out.print("This value must be an integer, please enter the number of years ahead again: ");
}
Add a simple if:
if (YEARS_AHEAD < 0 || YEARS_AHEAD > 1000000) {
// say something to the user, retry entering the number
}
Another option is to use the while cycle for this:
int YEARS_AHEAD = -1; // invalid value
while (YEARS_AHEAD < 0 || YEARS_AHEAD > 1000000) {
try {
System.out.print("Enter the amount of years ahead: ");
YEARS_AHEAD = Integer.parseInt(reader.nextLine());
}catch (NumberFormatException nfe) {
System.out.print("This value must be an integer, please enter the number of years ahead again: ");
}
}
Once you have read the input
YEARS_AHEAD = Integer.parseInt(reader.nextLine());
check using if-else whether the input is permitted or not.
if(YEARS_AHEAD < 0 || YEARS_AHEAD >1000000){
System.out.println("Invalid Input");
}else{
// do your processing here.
}