Try Catch Block Not Catching String Input (InputMismatchException) - java

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();

Related

trying to understand how to handle InputMismatchException and keep the program running

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!");
}
}
}

Having an incedibly tough time with a loop

I've copied part of the instructions below, and I can code pretty much every part on its own, but getting the control flow together is giving me massive doubts about my ability.
One of my biggest problems is the int gameChanger. Im supposed to immediately verify if it is a integer or not, and loop back if its not. But then Im also supposed to check to see if thebuser ever types "exit". But the input variable for my scanner instance is an integer... So Im stumped. I can use a try catch to check the missmatchexception once the input is being read in, but that doesnt solve the exit issue nor am I able to come up with solid logic to get the try catch to loop back if it indeed isnt an integer. Im thinking a do while loop but I havent gotten it to work.
Instructions:
You can whether the input is a number before attempting to consume it.
int num;
while (true) {
if (scanner.hasNextInt()) {
num = scanner.nextInt();
break;
} else {
// read whatever is there instead.
String line = scanner.nextLine();
if (line.equals("exit"))
System.exit(0);
System.out.println("Please enter a number");
}
}
System.out.println("Number entered " + num);
This gets the job done. Try it out.
import java.util.Scanner;
public class MyCode
{
public static void main(String[] args)
{
String gameInput = ".";
int gameNumber = 0;
boolean inputLoop = true;
Scanner input = new Scanner(System.in);
while(inputLoop == true)
{
try
{
System.out.print("Please enter a valid game number: ");
gameInput = input.next();
if(gameInput.equals("exit"))
{
System.out.println("Program will now end. Goodbye.");
inputLoop = false;
input.close();
}
gameNumber = Integer.parseInt(gameInput);
if(gameNumber >= 20001 && gameNumber <= 21230)
{
System.out.println("You have inputted a valid game number.");
inputLoop = false;
input.close();
}
}
catch(NumberFormatException e)
{
if(!gameInput.equals("exit"))
{
System.err.println("Invalid game number. Please try again.");
}
}
}
}
}

Looping around a try catch

In the below code I am attempting to allow the program to catch an exception for an invalid input from user but still allow the program to loop back to the start of the method once exception has been caught. However in my example once there is an exception the program terminates. How can I rectify this? Thank a lot in advance!
public static void add() {
// Setting up random
Random random = new Random();
// Declaring Integers
int num1;
int num2;
int result;
int input;
input = 0;
// Declaring boolean for userAnswer (Defaulted to false)
boolean correctAnswer = false;
do {
// Create two random numbers between 1 and 100
num1 = random.nextInt(100);
num1++;
num2 = random.nextInt(100);
num2++;
// Displaying numbers for user and getting user input for answer
System.out.println("Adding numbers...");
System.out.printf("What is: %d + %d? Please enter answer below", num1, num2);
result = num1 + num2;
do {
try {
input = scanner.nextInt();
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition");
// flush scanner
scanner.next();
correctAnswer=false;
}
} while (correctAnswer);
// Line break for code clarity
System.out.println();
// if else statement to determine if answer is correct
if (result == input) {
System.out.println("Well done, you guessed corectly!");
correctAnswer = true;
} else {
System.out.println("Sorry incorrect, please guess again");
}
} while (!correctAnswer);
}// End of add
I'm not quite sure about the exceptions part, but have you maybe though about just using if statements?
Scanner has a method 'hasNextInt' which you can use to check that the the input is na int. For example:
Scanner scan = new Scanner(System.in);
int i=0;
boolean correctAnswer = false;
while(correctAnswer == false){
if(scan.hasNextInt()){
i = scan.nextInt(); correctAnswer = true;
}else{ System.out.println("Invalid entry");
correctAnswer = false;
scan.next();
}
System.out.println(i);
}
Sorry that it doesn't actually directly answer your question, but I though you might want to know about this possible way too. :)
Instead of throw an exception maybe you can use the method hasNextInt() which returns true if the token is a number.
But if you want absolutely use the try catch block, you have to remove the scanner.next() instrsctions because when nothings available on the buffer, it's throws an NoSuchElementException
I think solution i am giving can be improved but this is simple modification to fix your code: (just add new condition variable to check if further input/ans attempts required)
Hope it helps - MAK
public class StackTest {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws InterruptedException{
// Setting up random
Random random = new Random();
// Declaring Integers
int num1;
int num2;
int result;
int input;
input = 0;
// Declaring boolean for userAnswer (Defaulted to false)
boolean correctAnswer = false;
//MAK: Add new condition for checking need of input
boolean needAnswer = true;
do {
// Create two random numbers between 1 and 100
num1 = random.nextInt(100);
num1++;
num2 = random.nextInt(100);
num2++;
// Displaying numbers for user and getting user input for answer
System.out.println("Adding numbers...");
System.out.printf("What is: %d + %d? Please enter answer below",
num1, num2);
result = num1 + num2;
while(needAnswer){
try {
input = scanner.nextInt();
needAnswer = false;
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition");
// flush scanner
scanner.next();
needAnswer = true;
}
} ;
// Line break for code clarity
System.out.println();
// if else statement to determine if answer is correct
if (result == input) {
System.out.println("Well done, you guessed corectly!");
correctAnswer = true;
} else {
System.out.println("Sorry incorrect, please guess again");
needAnswer = true;
}
} while (!correctAnswer);
}
}
If you want to have the following:
1) Ask the user how much is x + y
2) Let the user answer
3) If answer is invalid (e.g. user typed in "www"), let the user type his answer to question 1) again
than you should replace your inner do-while loop with the following:
boolean validInput = true;
do {
try {
input = scanner.nextInt();
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition. Please enter your answer again.");
// flush scanner
scanner.next();
validInput = false;
}
} while (!validInput);

How to repeat until the user enters an integer?

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.

Try-Catch inside a loop

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...

Categories

Resources