Infinite Loop in My Exception Handling? [duplicate] - java

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 5 years ago.
I'm trying to validate a user's input on a menu. Options are 1, 2, 3, and 4. I'm trying to handle the InputMismatchException error when they enter in a letter. I can't see what I'm doing wrong to make my code get stuck in an infinite loop.
System.out.println("What will be your starting balance?");
double startingBalance =0;
boolean check = false;
while(!check) {
try {
startingBalance = input.nextDouble();
check = true;
}
catch (InputMismatchException e) {
System.out.println("Invalid input!");
//startingBalance = 0;
//e.printStackTrace();
//check = false;
}
}
It looks like it get into the catch part, but loops through that repeatedly instead of going back to the try. I tried doing input.nextDouble();
to clear input buffer, but did nothing. Any help would be greatly appreciated.

You can use input.nextLine(); to clear your Scanner in your catch block:
while (!check) {
try {
startingBalance = input.nextDouble();
check = true;
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
input.nextLine();//this will clear your Scanner and repeat again
}
}
Can I ask why you used nextLine() as opposed to nextDouble() ?
because nextLine move the Scanner to the next line

you need to set boolean check = false after first check and also use input.nestLine()

Related

Java Try-catch block, Catch block does not re-prompt the user for a new value [duplicate]

This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 6 years ago.
I am new to Java and would like to ask you a question.
I have written the below code where "numOfThreads" should be assigned a valid int value by the user through the Console.
However, I would like to achieve a result where if the input is incorrect and we go in the catch block, the user should be re-prompted to enter "numOfThreads" until it is of correct type and range.
For some reason I seem to go into infinite loop. Can you please assist? Thanks :)
import java.util.Scanner;
public class Main {
public static void main(String args[]){
int numOfThreads;
boolean promptUser = true;
Scanner keyboard = new Scanner(System.in);
while (promptUser)
{
try{
numOfThreads = keyboard.nextInt();
promptUser = false;
}
catch(Exception e){
System.out.println("Entry is not correct and the following exception is returned: " + e);
numOfThreads = keyboard.nextInt(); // DOES NOT SEEM TO BE ASKING FOR A NEW INPUT
}
}
}
}
it doesn´t because nextInt tries to consume the last token. When there is an invalid input it can´t consume it. As a result a following nextInt call wont be able to consume it either. write a keyboard.nextLine before numOfThreads = keyboard.nextInt(); and you are fine.
catch(Exception e){
System.out.println("Entry is not correct and the following exception is returned: " + e);
// this consumes the invalid token now
keyboard.nextLine();
numOfThreads = keyboard.nextInt(); // It wasn´t able to get the next input as the previous was still invalid
// I´d still rewrite it a little bit, as this keyboard.nextInt is now vulnerable to throw a direct exception to the main
}

Scanner type checking in method [duplicate]

I have read user input that must be only of type int, the problem comes when the user enters letter instead of a int. I know how to handle the exception, but I would like to return the scanner read where the user has made a mistake. How can I do?
I already tried with an infinite loop, but it does not work.
try{
System.out.print("enter number: ");
value = scanner.nextInt();
}catch(InputMismatchException e){
System.err.println("enter a number!");
}
While other answers give you correct idea to use loop you should avoid using exceptions as part of your basic logic. Instead you can use hasNextInt from Scanner to check if user passed integer.
System.out.print("enter number: ");
while (!scanner.hasNextInt()) {
scanner.nextLine();// consume incorrect values from entire line
//or
//tastiera.next(); //consume only one invalid token
System.out.print("enter number!: ");
}
// here we are sure that user passed integer
int value = scanner.nextInt();
A loop is the right idea. You just need to mark a success and carry on:
boolean inputOK = false;
while (!inputOK) {
try{
System.out.print("enter number: ");
numAb = tastiera.nextInt();
// we only reach this line if an exception was NOT thrown
inputOK = true;
} catch(InputMismatchException e) {
// If tastiera.nextInt() throws an exception, we need to clean the buffer
tastiera.nextLine();
}
}

try/catch infinite loop? [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 5 years ago.
Help, I am completely new to java and I am trying to create a loop that will ask for an input from the user which is to be a number. If the user enters anything other than a number I want to catch the exception and try again to get the correct input. I did this with a while loop however it does not give the opportunity after the error for the user to type in anything it loops everything else but that. Please help me to see understand what is wrong and the correct way to do this... Thank you. This is what I have:
import java.util.Scanner;
import java.util.InputMismatchException;
public class simpleExpressions {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
while ( true ) {
double numOne;
System.out.println("Enter an Expression ");
try {
numOne = keyboard.nextInt();
break;
} catch (Exception E) {
System.out.println("Please input a number only!");
} //end catch
} //end while
} //end main
while ( true )
{
double numOne;
System.out.println("Enter an Expression ");
try {
numOne = keyboard.nextInt();
break;
}
catch (Exception E) {
System.out.println("Please input a number only!");
}
This suffers from several problems:
numOne hasn't been initialized in advance, so it will not be definitely assigned after the try-catch, so you won't be able to refer to it;
if you plan to use numOne after the loop, then you must declare it outside the loop's scope;
(your immediate problem) after an exception you don't call scanner.next() therefore you never consume the invalid token which didn't parse into an int. This makes your code enter an infinite loop upon first encountering invalid input.
Use keyboard.next(); or keyboard.nextLine() in the catch clause to consume invalid token that was left from nextInt.
When InputMismatchException is thrown Scanner is not moving to next token. Instead it gives us opportunity to handle that token using different, more appropriate method like: nextLong(), nextDouble(), nextBoolean().
But if you want to move to other token you need to let scanner read it without problems. To do so use method which can accept any data, like next() or nextLine(). Without it invalid token will not be consumed and in another iteration nextInt() will again try to handle same data throwing again InputMismatchException, causing the infinite loop.
See #MarkoTopolnik answer for details about other problems in your code.
You probably want to use a do...while loop in this case, because you always want to execute the code in the loop at least once.
int numOne;
boolean inputInvalid = true;
do {
System.out.println("Enter an expression.");
try {
numOne = keyboard.nextInt();
inputInvalid = false;
} catch (InputMismatchException ime) {
System.out.println("Please input a number only!");
keyboard.next(); // consume invalid token
}
} while(inputInvalid);
System.out.println("Number entered is " + numOne);
If an exception is thrown then the value of inputInvalid remains true and the loop keeps going around. If an exception is not thrown then inputInvalid becomes false and execution is allowed to leave the loop.
(Added a call to the Scanner next() method to consume the invalid token, based on the advice provided by other answers here.)

Catching an InputMismatchException until it is correct [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
How to use Scanner to accept only valid int as input
(6 answers)
Closed 5 years ago.
I am trying add catch blocks to my program to handle input mismatch exceptions. I set up my first one to work inside of a do while loop, to give the user the opportunity to correct the issue.
System.out.print("Enter Customer ID: ");
int custID=0;
do {
try {
custID = input.nextInt();
} catch (InputMismatchException e){
System.out.println("Customer IDs are numbers only");
}
} while (custID<1);
As it stands, if I try to enter a letter, it goes into an infinite loop of "Customer IDs are numbers only".
How do I make this work properly?
Be aware that When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
To avoid "infinite loop of "Customer IDs are numbers only".", You need to call input.next(); in the catch statement to to make it possible to re-enter number in Console
From
statement
catch (InputMismatchException e) {
System.out.println("Customer IDs are numbers only");
To
catch (InputMismatchException e) {
System.out.println("Customer IDs are numbers only");
input.next();
}
Example tested:
Enter Customer ID: a
Customer IDs are numbers only
b
Customer IDs are numbers only
c
Customer IDs are numbers only
11
What's happening is that you catch the mismatch, but the number "wrong input" still needs to be cleared and a .next() should be called. Edit: since you also require it to be greater than or equal to 1 per your do/while
boolean valid = false;
while(!valid) {
try {
custID = input.nextInt();
if(custID >= 1) //we won't hit this step if not valid, but then we check to see if positive
valid = true; //yay, both an int, and a positive one too!
}
catch (InputMismatchException e) {
System.out.println("Customer IDs are numbers only");
input.next(); //clear the input
}
}
//code once we have an actual int
Why not use a scanner object to read it with Scanner.readNextInt()?
I got it, this is solution you are looking for:
public class InputTypeMisMatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int custID=0;
System.out.println("Please enter a number");
while (!input.hasNextInt()) {
System.out.println("Please enter a number");
input.next();
}
custID = input.nextInt();
}
}

Java.util.scanner error handling

I'm helping a friend with a java problem. However, we've hit a snag. We're using Java.Util.Scanner.nextInt() to get a number from the user, asking continiously if the user gives anything else. Only problem is, we can't figure out how to do the error handeling.
What we've tried:
do {
int reloop = 0;
try {
number = nextInt();
} catch (Exception e) {
System.out.println ("Please enter a number!");
reloop ++;
}
} while(reloop != 0);
Only problem is, this loops indefinatly if you enter in something not a number.
Any help?
You can use hasNextInt() to verify that the Scanner will succeed if you do a nextInt(). You can also call and discard nextLine() if you want to skip the "garbage".
So, something like this:
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt()) {
System.out.println("int, please!");
sc.nextLine();
}
int num = sc.nextInt();
System.out.println("Thank you! (" + num + ")");
See also:
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
The problem with your code, in addition to the unnecessarily verbose error handling because you let nextInt() throw an InputMismatchException instead of checking for hasNextInt(), is that when it does throw an exception, you don't advance the Scanner past the problematic input! That's why you get an infinite loop!
You can call and discard the nextLine() to fix this, but even better is if you use the exception-free hasNextInt() pre-check technique presented above instead.
if the number is non-int , exception will pop, if not reloop will become 1 , and loop will exit
int reloop = 0;
do {
try {
number = nextInt();
reloop ++;
} catch (Exception e) {
System.out.println ("Please enter a number!");
}}
while(reloop == 0);

Categories

Resources