This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 5 years ago.
I am facing java.util.InputMismatchException;
I catch InputMismatchException but I don't understand why it is going into infinite loop after taking first wrong input and the output goes on like this:
enter two integers
exception caught
this goes on repeating
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int flag = 0;
while (flag != 1) {
try {
System.out.println("enter two integers");
int a = sc.nextInt();
int b = sc.nextInt();
int result = a + b;
flag = 1;
System.out.println("ans is" + result);
} catch (NumberFormatException e) {
System.out.println("exception caught");
} catch (InputMismatchException e) {
System.out.println("exception caught");
}
}
}
You need to clear the buffer so that it is not invalid for nextInt() after the exception is thrown. Add a finally block and call sc.nextLine() within it:
while (flag != 1) {
try {
System.out.println("enter two integers");
int a = sc.nextInt();
int b = sc.nextInt();
int result = a + b;
flag = 1;
System.out.println("ans is" + result);
} catch (NumberFormatException e) {
System.out.println("exception caught");
} catch (InputMismatchException e) {
System.out.println("exception caught");
} finally { //Add this here
sc.nextLine();
}
}
Working example: https://ideone.com/57KtFw
If you press the enter key you need to consume this character too
int a = sc.nextInt();
int b = sc.nextInt();
sc.nextLine ();
then you can enter
2 3 <CR>
In your code you are catching InputMisMatchException and you are just printing a message which will result in again going to your while loop.
int a = sc.nextInt();
int b = sc.nextInt();
When either of these lines throw the exception your flag=1 will not be set and you will be in an infinite loop. Correct your exception handling and either break out of loop or clear your scanner input by reading it as string.
Related
I wanted to print the multiplication table of a number. So I made a while(true) block to ontinously take inputs from the user. I also made a try and catch block, so that I could handle the exeptions.
Here is my code below :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Getting the multiplication table of any number");
while (true) {
try {
System.out.println();
System.out.print("Enter a number: ");
long number = scanner.nextLong();
for (byte num = 1; num < 11; num++) {
System.out.println(number + "X" + num + " = " + (number * num));
}
System.out.println();
System.out.println();
} catch (Exception e) {
System.out.println("Please enter a valid input.");
}
}
}
}
When I run the programm, it run fine till I introduce just one error. Then it just gives the output:
Enter a number: Please enter a valid input.
Both the statements on the same line, And just continuosly prints the line without any delay or without letting me give it an input.
Why is this happening and how can I correct it?
You can change your catch block as:
catch (Exception e) {
System.out.println("Please enter a valid input.");
scanner.next();
}
I am learning to handle exception and In try block if i get character input in arr[i] then I want the catch block to ask for array input again.
But the catch block array input code is throwing error.
package Day2;
import java.util.Scanner;
public class LargestinArray {
public static void main(String[] args) {
System.out.println("enter 5 number");
Scanner scanner=new Scanner(System.in);
int arr[]=new int[5];
try{
for (int i=0;i<5;i++){
arr[i]=scanner.nextInt();
}
}catch (Exception e){
System.out.println("error");
for (int i=0;i<5;i++){
arr[i]=scanner.nextInt();
}
}
findLarge(arr);
}
private static void findLarge(int[] arr) {
int max=arr[0],min=arr[0];
for (int i=0;i<arr.length;i++){
if (arr[i]>max){
max=arr[i];
}
if (arr[i]<min){
min=arr[i];
}
}
System.out.println("max is"+max+"min is"+min);
}
}
This is the error i am getting
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Day2.LargestinArray.main(LargestinArray.java:19)
The code below will try reading the scanner input and it'll try again and again until it succeeds reading 5 ints in a row. If you don't necessarily want the correct inputs to be consecutive write a comment below and I'll edit this answer.
boolean isDone = false;
while (!isDone) {
try {
for (int i = 0; i < 5; i++){
arr[i] = scanner.nextInt();
}
isDone = true;
} catch (Exception e){
System.out.println("error");
}
}
Here's a way to read input, looping indefinitely until five consecutive integers are found.
Note that instead of using scanner.nextInt(), I'm using scanner.next(). The reason is that nextInt() will leave unconsumed non-integer input still sitting on the scanner – that is, if there's something non-integer waiting such as a string, that string still be there when you call nextInt() again. You could make scanner.nextInt() work by calling scanner.next() inside the catch block but there might be more to consider about whether that creates any other issues.
private static int[] getNumbers() {
Scanner scanner = new Scanner(System.in);
while (true) {
try {
int[] numbers = new int[5];
for (int i = 0; i < 5; i++) {
String next = scanner.next();
numbers[i] = Integer.parseInt(next);
}
return numbers;
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can call the function like this:
int[] numbers = getNumbers();
System.out.println("numbers: " + Arrays.toString(numbers));
This question already has answers here:
What's the best way to check if a String represents an integer in Java?
(40 answers)
Closed 8 years ago.
import java.util.Scanner;
public class test {
/**
* #param args
*/
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
boolean US1 = false;
boolean game;
int score = 1;
int wage = 0;
int fin_score = 0;
String ans;
if (US1 == false) {
game = false;
System.out.println (score);
System.out.println("Enter a wager");
wage = input.nextInt();
}
if (wage < score) {
System.out.println ("What is the capital of Liberia?");
ans = input.next();
if (ans.equalsIgnoreCase("Monrovia")) {
System.out.println ("You got it right!");
System.out.println ("Final score " + fin_score);
}
}
}
}
I have found a bunch of solutions using InputMismatchException and try{}catch{} but they never work when they are implemented in my code. is there a way to implement these here? I am trying to make a loop that iterates until the wage entered is an integer
You can have multiple catch exceptions in your code to check for bad input. For example
try{
wage = input.nextInt();
catch (InputMismatchException e){
System.out.print(e.getMessage());
//handle mismatch input exception
}
catch (NumberFormatException e) {
System.out.print(e.getMessage());
//handle NFE
}
catch (Exception e) {
System.out.print(e.getMessage());
//last ditch case
}
Any of these would work fine for Scanner errors, but InputMismatchException is the best to use. It would help your case a great deal if you included the non-working code with the try-catch blocks.
First of all, You should be using Scanner.nextLine, because Scanner.nextInt uses spaces and newlines as delimiters, which is probably not what you want (any thing after a space will be left on the scanner, breaking any next reads).
Try this instead:
boolean valid = false;
System.out.print("Enter a wager: "); //Looks nicer when the input is put right next to the label
while(!valid)
try {
wage = Integer.valueOf(input.nextLine());
valid = true;
} catch (NumberFormatException e) {
System.out.print("That's not a valid number! Enter a wager: ");
}
}
Yes! There is a good way to do this:
Scanner input = new Scanner(System.in);
boolean gotAnInt = false;
while(!gotAnInt){
System.out.println("Enter int: ");
if(input.hasNextInt()){
int theInt = input.nextInt();
gotAnInt = true;
}else{
input.next();
}
}
I would like the program to re-do the while loop when it catches the exception - the exception being receiving a number zero. Instead it continues a while loop with the code below, I would like it to ask for the user input again until the user inputs a number that is different by zero.
import java.util.InputMismatchException;
import java.util.Scanner;
public class whilePerjashtim {
public static int division(int a, int b){
return a/b;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a, b;
System.out.println("Enter a value: ");
a = s.nextInt();
while(true){
try
{
System.out.println("Enter b value");
b = s.nextInt();
System.out.println("Sum of division is: " + division(a,b));
}
catch(ArithmeticException e)
{
System.err.println("Don't divide by zero!!!");
}
catch (java.util.InputMismatchException e)
{
System.err.println("Enter just a Number!!!");
}
finally
{
System.out.println();
}
}
}
}
Use something of the following form (not exact Java for your homework problem)
boolean validInput = false;
while (!validInput) {
.. get input
.. set validInput = true if no error
.. catch error
.. print try again message
}
You can set a boolean value, that determines, if the while loop ends succesfully. Then in every loop you start by assuming the value is true and when an exception is raised, you set it to false.
boolean success = false;
while(success == false){
success = true;
try {
System.out.println("Enter b value");
b = s.nextInt();
System.out.println("Sum of divison is: " + division(a,b));
}
catch(ArithmeticException e) {
System.err.println("Dont divide by zero!!!");
success = false;
}
}
Define a boolean outside of your while loop, and use it for the while's condition.
Assuming I understood your question correctly, you want to stay in the loop if the user's input threw an exception, ie it was invalid input, and you want to break out of the loop when you get valid input from the user.
boolean gotValidInput = false;
while (!gotValidInput) {
try {
System.out.println("Enter b value");
b = s.nextInt();
gotValidInput = true;
System.out.println("Sum of divison is: " + division(a,b));
} catch(ArithmeticException e) {
System.err.println("Dont divide by zero!!!");
} catch (java.util.InputMismatchException e) {
System.err.println("Enter just a Number!!!");
} finally {
System.out.println();
}
}
In this implementation, your two exceptions would both be thrown before gotValidInput = true; gets evaluated, so it would only get set to true if no exceptions were thrown.
You can put extra outter loop, like
while (true) {
System.out.println("Enter a value: ");
a = s.nextInt();
while(true) {
/// terminate the loop in case of problem with a, and allow a user to re done
}
}
Cleaned up the warnings and moved s to ouside the main method and defined it as static. It appears the s is a resource leak if within the main and is never closed.
import java.util.InputMismatchException;
import java.util.Scanner;
public class whilePerjashtim {
private static Scanner s;
public static int division(int a, int b) {
return a / b;
}
public static void main(String[] args) {
int a, b;
s = new Scanner(System.in);
System.out.println("Enter a value: ");
a = s.nextInt();
boolean input = false;
while (input == false) {
try {
System.out.println("Enter b value");
b = s.nextInt();
System.out.println("Sum of division is: " + division(a, b));
input = true;
}
catch (ArithmeticException e) {
System.err.println("Don't divide by zero!!!");
}
catch (InputMismatchException e) {
System.err.println("Enter just a Number!!!");
}
finally {
System.out.println();
}
}
}
}
You need to handle the erroneous input as well if you want the while loop to continue properly: You need to get rid of the erroneous input at the end of each catch block. Adding continue will simply make the loop run again until the user gives the correct input.
catch (InputMismatchException e)
{
System.err.println("Enter just a Number!!!");
//add this
s.nextLine();
continue;
}
I am learning Java and am learning I/O w/ java.util.Scanner. Specifically I am learning Scanner methods.
import java.util.Scanner;
public class ScannerTest {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int result;
while (s.hasNextInt()) {
result += s.nextInt();
}
System.out.println("The total is " + result);
}
}
Because you're checking only
while (s.hasNextInt())
You could use try catch to catch the exception (see documentation here) you get when the program quits, so you can show your error message in the catch block without making the program close.
Perhaps you should try parsing each line:
public static void main(String args[]){
int sum = 0;
final Scanner scanner = new Scanner(System.in);
System.out.println("Enter a series of integers. Press 'q' to quit.");
while(true){
final String line = scanner.nextLine();
if(line.equals("q"))
break;
try{
final int number = Integer.parseInt(line);
sum += number;
}catch(Exception ex){
System.err.printf("Invalid: %s | Try again\n", ex.getMessage());
}
}
System.out.printf("The sum is %,d" , sum);
}
The idea is to read input line by line and attempt parsing their input as an integer. If an exception is thrown (meaning they entered an invalid integer) it would throw an exception in which you could handle in what ever way you want to. In the sample above, you are simply printing the error message and prompting the user to type in another number.
You can do this for the while loop (not tested though):
while (s.hasNextLine()) {
String line = s.nextLine();
int parsedInteger;
try {
parsedInteger = Integer.parseInt(line);
} catch(NumberFormatException numEx) {
if(line.startsWith("q")) break;
else {
System.out.println("please enter valid integer or the character 'q'.");
continue;
}
}
result += parsedInteger;
}
s.close();
Instead of scanning for int's you can scan for lines and then then parse each line as an int. I feel the advantage of this approach is that if any of your int's are malformed you can then handle them appropriately by say displaying an error message to the user.
OR, based on the answer by pinckerman, you can also do this.
while (s.hasNextInt()) {
try {
result += s.nextInt();
} catch(InputMismatchException numEx) {
break;
}
}
s.close();
A smart way you can do it and I've tried before is you use Integer.parseInt(String toParse); This returns an int and will reject all non numerical chars.
while (scanner.hasNextInt()) {
int i = Integer.parseInt(scanner.nextInt());
result += i;
if (result < 2147483648 && result > -2147483648) {
try{
throw new IndexOutOfBoundsException();
catch (Exception e) {e.printStackTrace();}
}
Try the following way:
int result = input.nextInt;
this will define your variable for result.
The only problem in your code is "not initializing" result. Once you initialized code will work properly. However, please do not forget you need to tell compiler EOF. Compiler can only understand the stop of the input on the console by EOF. CTRL Z is EOF for windows Eclipse IDE.