A Confusing Issue with nextLong() method in java.util.Scanner class - java

I am trying to run a simple code which will take an account number as the long type from the user through nextLong() method.Now if the user has given the account_number(long accNo) as string_type or character_type instead of long_type value then the InputMismatchException is thrown.That is also fine,because I am aware of the fact that nextLong() method can throw InputMismatchException along with NoSuchElementException and IllegalStateException.But after that when I am expecting that after getting InputMismatchException the loop will revisit and ask me to give the account_number(long accNo) as long value again! then the problem occurs.It is not asking me to give any value,instead an infinite loop is running along with the exception again & again.!!
package genericsandcollection;
import java.util.*;
public class ScannerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
boolean b=true;
while(b){
try{
System.out.println("Enter Your Account Number..: ");
long accNo=sc.nextLong();
System.out.println(accNo);
b=false;
}catch(InputMismatchException | IllegalStateException e){
e.printStackTrace();
System.out.println(e);
System.out.println("Wrong syntax");
}
}
}
}
Why is it happening ? Is not nextLong() smart enough to handle a situation inside a loop ! If I use Long.parseLong(sc.next()) instead of sc.nextLong(),then everything is alright as parseLong() is throwing NumberFormatException i.e. until I will give the account number as long_type it keeps asking the user to give the account_number as long_type value.Really Strange !!!! If anybody has any concern,please help.Thank you.

Do not close the scanner in the catch block or you won't be able to use it again.

You shouldn't close the Scanner because as well as meaning you cannot use the Scanner anymore it will also close System.in. Your infinite loop is because using any other method than nextLine will leave a line break (from pressing 'enter' to submit) at the end of the input buffer. This will cause nextLong to always throw an exception.
Calling nextLine will advance the Scanner. The following is a short example that shows this (adapted from a very similar answer I wrote).
do {
try {
accNo = sc.nextLong();
break;
} catch (InputMismatchException e) {
} finally {
sc.nextLine(); // always advances (even after the break)
}
System.out.print("Input must be a number: ");
} while (true);

Related

How to use Try/Catch to prevent String input where an Int is needed

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package freetime;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* #author Andy
*/
public class NewClass {
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
int userInput=0,notInt=0,newInput=0;
System.out.println("Enter a integer number");
while (notInt == 0){
try {
newInput=scan.nextInt();
userInput=newInput;
if (userInput != newInput){
notInt=0;
}
if (userInput == newInput){
notInt=1;
}
}
catch(InputMismatchException e){
System.out.println("That is not an integer, please try again." );
}
}
System.out.println(userInput);
}
}
I am trying to prevent a string input and allow the user to re input as an int. i cannot seem to get it to work properly, i also did this without the while loop. I think my understanding of how the Try Mismatch functions work is causing some issues.
Thanks for the help.
Scanner scan=new Scanner(System.in);
int userInput=0,notInt=0,newInput=0;
boolean runL=true;
while (runL){
System.out.println("Enter a integer number");
if (scan.hasNextInt()){
userInput=scan.nextInt();
runL=false;
}
else {
System.out.println("That is not an integer, please try again.");
}
}
System.out.println(userInput);
So i changed the code to this but I am still running into the loop continuing to go after something other than an int is entered. What am i doing wrong?
int userInput=0,notInt=0,newInput=0;
boolean runL=true;
while (runL){
Scanner scan=new Scanner(System.in);
System.out.println("Enter a integer number");
if (scan.hasNextInt()){
userInput=scan.nextInt();
runL=false;
}
else {
System.out.println("That is not an integer, please try again.");
}
}
System.out.println(userInput);
I've found the problem, I needed to create the scanner object inside of the While loop. Thanks for the help!
I think my understanding of how the Try Mismatch functions work is causing some issues.
You are probably right there ...
When I remove some of the "strange" code from your try / catch statement it looks like this:
try {
newInput = scan.nextInt();
// do stuff
} catch (InputMismatchException e){
// do other stuff
}
Here's what that actually means:
Call scan.nextInt()
If the call succeeds (i.e. it doesn't throw an exception), then:
assign the result to newInput
"do stuff"
If the call failed, AND it threw a InputMismatchException, then:
"do other stuff"
So, based on that, you don't need to do anything in "do stuff" to test if you just got a valid input. You know that is the case.
And likewise, any stuff that needs to be do in the case where you didn't get a valid input should be in "do other stuff".
Having said that, Jon Skeet's suggestion to look at the hashNextInt method is spot on. If you use that the right way, you won't get an exception at all. The code will be much simpler.
And Jon is also correct that you should be using the boolean type for your true / false logic. (That is what the type is intended for!)
Use Integer.parseInt(input) in try block.
If input is not an int, then it will throw an exception and catch the exception in catch{} block.
Your while loop should look like this:
while (notInt == 0){
try {
newInput=Integer.parseInt(scan.nextLine());
userInput=newInput;
notInt=1;
}
catch(NumberFormatException e){
System.out.println("That is not an integer, please try again." );
}
}
Your code doesn't work because when a InputMismatchException is thrown, the token that causes the exception isn't actually read. So the loop is reading the same thing every iteration.
nextLine however, almost always reads the whole line as a string (except when there's no line). You put the string that is read into Integer.parseInt to turn it into an int. If it can't be turned into an int, a NumberFormatException will be thrown.
However, you should not use exceptions as a way of validating inputs because it's slow. You can try this approach with regex:
while (notInt == 0){
String line = scan.nextLine();
Pattern p = Pattern.compile("-?\\d+");
if (p.matcher(line).matches()) {
userInput = Integer.parseInt(line);
notInt = 1;
} else {
System.out.println("Please try again");
}
}

How do I take input along with handling exceptions?

I want to take an integer input from the user. I am using a try-catch exception so that if the input is not an int it asks the user for another input. I have written the following code:
while (flag==true) {
try {
System.out.println("Enter the encryption key!");
k = input.nextInt();
flag = false;
}
catch (InputMismatchException ex) {
System.out.println("Please enter integer value!(");
}
}
But when an exception occurs the loop keeps on printing
"Enter the encryption key!"
"Please enter integer value!"
infinitely because the scanner input does not wait to take another input.
How can I tackle with this problem?
You could try to use
input.nextLine()
because then it waits until you press enter. But then you need to parse it to an int if i remember correctly.
You should call next inside the catch clause, this will solve the problem.
See the docs - Scanner:
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.
Without having next in the catch clause, input.nextInt(); will keep reading the same token, adding next will consume that token.
You should go with suggestion of Maroun Maroun that looks more clean to me.
One other way is to re-initialize the Scanner in loop.
boolean flag = false;
while (!flag) {
try {
input = new Scanner(System.in);//Initialize it here
//....

try-catch statement not returning to try block when catching exception

I have a method that a wrote. This method just scans for a user entered integer input. If the user enters a character value it will throw an input mismatch exception, which is handled in my Try-Catch statement. The problem is that, if the user inputs anything that is not a number, and then an exception is thrown, I need the method to loop back around to ask the user for input again. To my understanding, a Try catch statement automatically loops back to the Try block if an error is caught. Is this not correct? Please advise.
Here is my method (it's pretty simple):
public static int getMask() {
//Prompt user to enter integer mask
Scanner keyboard = new Scanner(System.in);
int output = 0;
try{
System.out.print("Enter the encryption mask: ");
output = keyboard.nextInt();
}
catch(Exception e){
System.out.println("Please enter a number, mask must be numeric");
}
return output;
}//end of getMask method
Here is how the method is implemented into my program:
//get integer mask from user input
int mask = getMask();
System.out.println("TEMP mask Value is: " + mask);
/***********************************/
Here is my updated code. It creates an infinate loop that I can't escape. I don't understand why I am struggling with this so much. Please help.
public static int getMask() {
//Prompt user to enter integer mask
Scanner keyboard = new Scanner(System.in);
int output = 0;
boolean validInput = true;
do{
try {
System.out.print("Enter the encryption mask: ");
output = keyboard.nextInt();
validInput = true;
}
catch(InputMismatchException e){
System.out.println("Please enter a number, mask must be numeric");
validInput = false;
}
}while(!(validInput));
return output;
/********************/FINAL_ANSWER
I was able to get it finally. I think I just need to study boolean logic more. Sometimes it makes my head spin. Implementing the loop with an integer test worked fine. My own user error I suppose. Here is my final code working correctly with better exception handling. Let me know in the comments if you have any criticisms.
//get integer mask from user input
int repeat = 1;
int mask = 0;
do{
try{
mask = getMask();
repeat = 1;
}
catch(InputMismatchException e){
repeat = 0;
}
}while(repeat==0);
To my understanding, a Try catch statement automatically loops back to the Try block if an error is caught. Is this not correct?
No this is not correct, and I'm curious as to how you arrived at that understanding.
You have a few options. For example (this will not work as-is but let's talk about error handling first, then read below):
// Code for illustrative purposes but see comments on nextInt() below; this
// is not a working example as-is.
int output = 0;
while (true) {
try{
System.out.print("Enter the encryption mask: ");
output = keyboard.nextInt();
break;
}
catch(Exception e){
System.out.println("Please enter a number, mask must be numeric");
}
}
Among others; your choice of option usually depends on your preferred tastes (e.g. fge's answer is the same idea but slightly different), but in most cases is a direct reflection of what you are trying to do: "Keep asking until the user enters a valid number."
Note also, like fge mentioned, you should generally catch the tightest exception possible that you are prepared to handle. nextInt() throws a few different exceptions but your interest is specifically in an InputMismatchException. You are not prepared to handle, e.g., an IllegalStateException -- not to mention that it will make debugging/testing difficult if unexpected exceptions are thrown but your program pretends they are simply related to invalid input (and thus never notifies you that a different problem occurred).
Now, that said, Scanner.nextInt() has another issue here, where the token is left on the stream if it cannot be parsed as an integer. This will leave you stuck in a loop if you don't take that token off the stream. To that end you actually want to use either next() or nextLine(), so that the token is always consumed no matter what; then you can parse with Integer.parseInt(), e.g.:
int output = 0;
while (true) {
try{
System.out.print("Enter the encryption mask: ");
String response = keyboard.next(); // or nextLine(), depending on requirements
output = Integer.parseInt(response);
break;
}
catch(NumberFormatException e){ // <- note specific exception type
System.out.println("Please enter a number, mask must be numeric");
}
}
Note that this still directly reflects what you want to do: "Keep asking until the user enters a valid number, but consume the input no matter what they enter."
To my understanding, a Try catch statement automatically loops back to the Try block if an error is caught. Is this not correct?
It is indeed not correct. A try block will be executed only once.
You can use this to "work around" it (although JasonC's answer is more solid -- go with that):
boolean validInput = false;
while (!validInput) {
try {
System.out.print("Enter the encryption mask: ");
output = keyboard.nextInt();
validInput = true;
}
catch(Exception e) {
keyboard.nextLine(); // swallow token!
System.out.println("Please enter a number, mask must be numeric");
}
}
return output;
Further note: you should NOT be catching Exception but a more specific exception class.
As stated in the comments, try-catch -blocks don't loop. Use a for or while if you want looping.

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

Figuring out how class Scanner and its exceptions work together in Java

I am looking at the example in How to Program in Java, 7e.
User inputs the data manually into object of class AccountRecord record
AccountRecord record = new AccountRecord();
Scanner input = new Scanner( System.in );
while ( input.hasNext() ) // loop until end-of-file indicator
{
try // output values to file
{
// retrieve data to be output
record.setAccount( input.nextInt() ); // read account number
record.setFirstName( input.next() ); // read first name
record.setLastName( input.next() ); // read last name
record.setBalance( input.nextDouble() ); // read balance
.............................................................
catch ( NoSuchElementException elementException )
{
System.err.println( "Invalid input. Please try again." );
input.nextLine(); // discard input so user can try again
} // end catch
}
I have hard time figuring out how catch ( NoSuchElementException elementException ) works. According to Java Documentation, NoSuchElementException is
Thrown by the nextElement method of an Enumeration to indicate that
there are no more elements in the enumeration.
So, why it would also throw an exception in case type mismatch between expected and what is actually entered, such as for record.setAccount(input.nextInt()), user inputs some text string?
Thanks !
For type mismatch problems, you should catch InputMismatchException. Since it inherits from NoSuchElementException, you will catch it by catching a NoSuchElementException (so the code as it is will catch it and work as expected). To me, that's a strange inheritance relationship, though.... Certainly does not represent an is-a relationship.
If you really want to differentiate both cases, catch an InputMismatchException before a NoSuchElementException.
Well each of the:
input.nextInt(); can throw the NoSuchElementException
if no other element is present.
Your Scanner object is actually an Enumeration.
From the javadoc:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
import java.util.*;
public class Assingnment {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("Enter a text: ");
Scanner scan=new Scanner(System.in);
String userinput= scan.next();
} catch(Exception e){
System.out.println("Wrong input");
}
}

Categories

Resources