I am using a while loop to make sure that the value entered to a scanner object is an integer as such:
while (!capacityCheck) {
try {
System.out.println("Capacity");
capacity = scan.nextInt();
capacityCheck = true;
} catch (InputMismatchException e) {
System.out.println("Capacity must be an integer");
}
}
however, if the user does not enter an integer, when it should go back and take another input it just repeatedly prints "Capacity" followed by the output in the catch without asking for more input. How do I stop this?
scan.nextLine();
Put this piece of code inside your catch block, to consume the non integer character along with the new line character which is stays in the buffer(hence, infinitely printing the catch sysout), in the case where you've given a wrong input.
Ofcourse, there are other cleaner ways to achieve what you want, but I guess that will require some refactoring in your code.
Use the following:
while (!capacityCheck) {
System.out.println("Capacity");
String input = scan.nextLine();
try {
capacity = Integer.parseInt(input );
capacityCheck = true;
} catch (NumberFormatException e) {
System.out.println("Capacity must be an integer");
}
}
Try this :
while (!capacityCheck) {
try {
System.out.println("Capacity");
capacity = scan.nextInt();
capacityCheck = true;
} catch (InputMismatchException e) {
System.out.println("Capacity must be an integer");
scan.nextLine();
}
}
Try putting this at the end of the loop -
scan.nextLine();
Or better to put it in the catch block.
while (!capacityCheck) {
try {
System.out.println("Capacity");
capacity = scan.nextInt();
capacityCheck = true;
} catch (InputMismatchException e) {
System.out.println("Capacity must be an integer");
scan.nextLine();
}
}
I see no need for a try/catch or capacityCheck as we have access to the method hasNextInt() - which checks if the next token is an int. For instance this should do what you want:
while (!scan.hasNextInt()) { //as long as the next is not a int - say you need to input an int and move forward to the next token.
System.out.println("Capacity must be an integer");
scan.next();
}
capacity = scan.nextInt(); //scan.hasNextInt() returned true in the while-clause so this will be valid.
Related
This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed last month.
So I'm building a program which takes ints from user input. I have what seems to be a very straightforward try/catch block which, if the user doesn't enter an int, should repeat the block until they do. Here's the relevant part of the code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Except {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean bError = true;
int n1 = 0, n2 = 0, nQuotient = 0;
do {
try {
System.out.println("Enter first num: ");
n1 = input.nextInt();
System.out.println("Enter second num: ");
n2 = input.nextInt();
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d",n1,n2, nQuotient);
}
}
If I enter a 0 for the second integer, then the try/catch does exactly what it's supposed to and makes me put it in again. But, if I have an InputMismatchException like by entering 5.5 for one of the numbers, it just shows my error message in an infinite loop. Why is this happening, and what can I do about it? (By the way, I have tried explicitly typing InputMismatchException as the argument to catch, but it didn't fix the problem.
You need to call next(); when you get the error. Also it is advisable to use hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.next();// Move to next other wise exception
}
Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.
Scanner scanner = new Scanner(System.in);
int n1 = 0, n2 = 0;
boolean bError = true;
while (bError) {
if (scanner.hasNextInt())
n1 = scanner.nextInt();
else {
scanner.next();
continue;
}
if (scanner.hasNextInt())
n2 = scanner.nextInt();
else {
scanner.next();
continue;
}
bError = false;
}
System.out.println(n1);
System.out.println(n2);
Javadoc of 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.
YOu can also try the following
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.next());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.next());
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
input.reset();
}
} while (bError);
another option is to define Scanner input = new Scanner(System.in); inside the try block, this will create a new object each time you need to re-enter the values.
To follow debobroto das's answer you can also put after
input.reset();
input.next();
I had the same problem and when I tried this. It completely fixed it.
As the bError = false statement is never reached in the try block, and the statement is struck to the input taken, it keeps printing the error in infinite loop.
Try using it this way by using hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.hasNextInt();
}
Or try using nextLine() coupled with Integer.parseInt() for taking input....
Scanner scan = new Scanner(System.in);
int num1 = Integer.parseInt(scan.nextLine());
int num2 = Integer.parseInt(scan.nextLine());
To complement the AmitD answer:
Just copy/pasted your program and had this output:
Error!
Enter first num:
.... infinite times ....
As you can see, the instruction:
n1 = input.nextInt();
Is continuously throwing the Exception when your double number is entered, and that's because your stream is not cleared. To fix it, follow the AmitD answer.
#Limp, your answer is right, just use .nextLine() while reading the input. Sample code:
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.nextLine());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.nextLine());
nQuotient = n1 / n2;
bError = false;
} catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d", n1, n2, nQuotient);
Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread.
Java Homework user input issue
Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.
I am trying to implement a (re)try-catch block.
Scanner sc = new Scanner(System.in);
while (true){
try {
t = sc.nextInt();
break;
} catch (Exception e) {
System.out.println("Please enter a whole number without any symbol(s)!");
}
}
But the problem here is that the control again goes into the catch block ones it reaches there and never attempts to execute the try block before that.
Here's how I solved it...
/*java.util.*/Scanner sc = new /*java.util.*/Scanner(System.in);
while(true)
{
if(sc.hasNextInt()){ t=sc.nextInt(); break;}
System.out.println("Please enter a whole number integer (between -2,147,483,649 and 2,147,483,648) without any symbol(s)!");
sc.nextLine(); // hasNextInt() only scans the current line in the buffer
}
when an invalid input is entered it goes to the catch block and infinitely executes the catch block without looping back to try block to get another input
It works when valid data is entered
public static double getInputNumber(Scanner input){
double num=0;
while(true) {
try {
num = input.nextDouble();
return num;
} catch (Exception ex) {
System.out.println("Invalid value entered.. Enter again : ");
}
}
}
expected - when an invalid value entered,show the user the error message and get a re-input until the users enters a valid value.
actual - when invalid value entered it displays the error message repeatedly in the screen without going for a re-input
It could well be that input has been closed, or the next token in the input is NOT a double. Either of these would cause an exception to be thrown, without advancing the input, so resulting in your infinite loop.
So you need to catch the cause of the error, to take the appropriate action - eg, something like :
public static double getInputNumber(Scanner input){
double num=0;
while(true) {
try {
num = input.nextDouble();
return num;
} catch (InputMismatchException ex) {
System.out.println("Invalid value entered.. Enter again : ");
} catch (NoSuchElementException ex) {
System.out.println("Input exhausted ");
return 0;
} catch (IllegalStateException ex) {
System.out.println("Scanner closed ");
return 0;
}
}
}
}
You could also use input.hasNextDouble() to check before calling nextDouble()
Just add input.next()
} catch (Exception ex) {
System.out.println("Invalid value entered.. Enter again : ");
input.next();
}
input.next() clears scanner.
So I am trying to write a method that checks if scanner input is an int, and loops errormessage until the user inputs an int. The method below works aslong as the usser doesn't give more than 1 wrong input. If I type muliple letters and then an int, the program will crash. I think it might have something to do with my try catch only catching 1 exception but not sure, and cant seem to get it to work. Does anyone know how I can fix this?
calling on method:
System.out.println("Write the street number of the sender: ");
int senderStreetNumber = checkInt(sc.nextLine);
method:
public static int checkInt (String value){
Scanner sc = new Scanner(System.in);
try{
Integer.parseInt(value);
} catch(NumberFormatException nfe) {
System.out.println("ERROR! Please enter a number.");
value = sc.nextLine();
checkInt(value);
}
int convertedValue = Integer.parseInt(value);
return convertedValue;
}
Something like this. Did not code it in an IDE, just from brain to keyboard.
Hope it helps. Patrick
Scanner sc = new Scanner(System.in);
int senderStreetNumber;
boolean ok = false;
while(!ok) {
System.out.println("Write the street number of the sender: ");
try {
senderStreetNumber = Integer.parseInt(sc.nextLine());
ok = true;
} catch (NumberFormatException nfe) {
System.out.println("ERROR! Please enter a number.");
}
}
Your logic of recursive is not good.
Let me try to explain your error...
The first time you get in the function you "check if the value is a int)
if not you to recurcive.
Lets say the second time is good.
then you cto the converted value
then the recurvice kicks in and you come back to the first time you get in the fucntion.
Then it does again the converted value and you don't catch that Exception so your application crash
This works.., just modified your program..tested
public static int checkInt(String value) {
Scanner sc = new Scanner(System.in);
try {
return Integer.parseInt(value);
}catch (Exception e) {
System.out.println("Error please enter correct..");
value = sc.nextLine();
return checkInt(value);
}
//int convertedValue = Integer.parseInt(value);
//return convertedValue;
}
Requirement:
Accept 10 numbers, input them into an array and then invoke a method to calculate and return the smallest. This program is suppose to be error proof so when a user enters an invalid entry, it notifies the user and reprompts. I am trying to use try catch but when an invalid entry is entered, ie a character, the scanner won't reprompt.
Any ideas?
Tried:
//Variables
double [] doubleArray = new double[10];
Scanner input = new Scanner(System.in);
//Prompt
System.out.println("This program will prompt for 10 numbers and display the smallest of the group");
//Get values
for (int i = 0; i < doubleArray.length; i++) {
try {
System.out.println("Please enter entry "+ (i+1));
doubleArray[i] = input.nextDouble();
} catch (InputMismatchException e) {
// TODO: handle exception
System.out.println("Please enter a rational number");
i--;
}
}
//Invoke method and display result
System.out.println("The smallest value is: "+index(doubleArray));
I don't see any call to input.nextLine(), which means nothing is ever consuming the \n entered by the user. There's a good example on scanner.nextLine usage here. If you add a call to it in your catch block, you should be all set.
Try calling input.nextLine(); in your catch. Then the \n will be taken from the input which let's you enter the next new number.
for(int i = 0; i < doubleArray.length; ++i) {
try {
doubleArray[i] = input.nextDouble();
} catch(Exception e) {
input.nextLine();
--i;
}
}
Try something like (and make sure you consume the whole line unless you want to allow multiple numbers to be input on the same line
boolean validEntry = false;
System.out.println("Enter a rational number: ");
while (!validEnry) {
try {
double value = input.nextDouble();
validEntry = true;
doubleArray[i] = value;
} catch (Exception e) {
System.out.println("Entry invalid, please enter a rational number");
}
}
...
You have to discard the false inputted data, add input.nextLine() in the catch block.