Java InputMismatchException
Asked Answered
D

6

8

I have this code and I want to catch the letter exception but it keeps having these errors:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at exercise_one.Exercise.main(Exercise.java:17)

And here is my code:

 System.out.print("Enter the number of students: ");

 students = input.nextInt(); 

 while (students <= 0) {

     try {

        System.out.print("Enter the number of students: ");

        students = input.nextInt();

     }

     catch (InputMismatchException e) {

        System.out.print("Enter the number of students");

     }
 }    
Depth answered 29/5, 2013 at 14:12 Comment(9)
The first students = input.nextInt(); is not inside the try block and your entering something that can't be stored in a an int.Philips
Yes it seems that this is the case but how can I check for both (letter and negative numbers exception) together?Depth
Easy. Just delete the first 2 lines of code you posted.Philips
If I delete the first two lines then I will get an error in the while loop because the students wont have a valueDepth
No you won't. students is an int, and they always have a value (default is 0).Philips
Error(18,19): variable students might not have been initialized when I run it without the first two linesDepth
is student int or Integer? Where you declare it, you can also assign 0 to it...Philips
the student is int. And the thing is that according to the exercise I have to givei the number of students manuallyDepth
What I've said before, plus add input.nextLine(); to the catch block.Philips
A
12

You can use a do-while loop instead to eliminate the first input.nextInt().

int students = 0;
do {
    try {
        // Get input 
        System.out.print("Enter the number of students: ");
        students = input.nextInt();
    } catch (InputMismatchException e) {
        System.out.print("Invalid number of students. ");
    }
    input.nextLine(); // clears the buffer
} while (students <= 0);

// Do something with guaranteed valid value 

Therefore all InputMismatchException can be handled in one place.

Astra answered 29/5, 2013 at 14:27 Comment(2)
This is good. Just remember to initialize your student variable before hand by setting it to 0. Otherwise you will get a "variable may not have been initialized" error during compilationRefrigerator
As written, if an InputMismatchException occurs, then it will print Enter the number of studentsEnter the number of students: . It may be good to replace the second print with something like System.out.println("Invalid input. Please enter a number.") so the user knows they have done something they weren't supposed to, and so you have a line between the prompt and the "error message".Cravens
B
4

from the doc

Scanner.nextInt Scans the next token of the input as an int. if the next token does not match the Integer regular expression, or is out of range

So it seems you are not entering any integer as input.

you can use

     while (students <= 0) {

         try {
            System.out.print("Enter the number of students: ");

            students = input1.nextInt();

         }

         catch (InputMismatchException e) {
             input1.nextLine();
         }
     } 
Bacteria answered 29/5, 2013 at 14:14 Comment(5)
I have declare it as an intDepth
If someone types in a string like abc, or he types in a number that cannot be expressed in an int, the nextInt() method will throw the exception. See docs.oracle.com/javase/7/docs/api/java/util/….Aftermost
I know that the only correct input is integers, but I wanted to catch the cases were the user presses 0 or negative number, which I fix it with the while loop and if the user presses maybe accidentaly a letter instead of a number. In that case I would like to be handled correcty and the code does not breakDepth
have you managed to solve this? if there is any problem you can update the questionBacteria
how can I catch the letter and the negative or zero number the same time? because I think the error is with the while loop.Depth
S
0

Reading data from Scanner and assigning it to Int type. Since you are supplying String this will throw exception. To handle this situation you must write your snippet inside Try- Catch block only.

Signalize answered 12/4, 2020 at 14:37 Comment(0)
H
0

If you wanna be sure about being integer for all input you can try this:

while(true) {
            try {
                System.out.print("Kolon sayısını giriniz: ");
                c = scan.nextInt();
                
            } catch (Exception e) {
                System.out.print("Geçersiz giriş.. ");
                scan.nextLine();
                continue;
            }
            break;
        }


// or this...
while(true) {
            System.out.print("Give me a number");
            try {
                input = scan.nextInt();
                break;
            } catch (Exception e) {
                System.out.print("There was mismatch");
                scan.nextLine();
            }
        }
Hephzipa answered 19/6, 2021 at 8:23 Comment(0)
V
0

John Stef,

The method nextInt() just Throws the following exceptions:

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

If you need/want throw another one type of exception you got to specify your own exception. Use throw statement. Here's an example of a throw statement.

throw someThrowableObject;

For example:

try {
    System.out.print("Enter the number of students: ");
    students = input.nextInt();
    if(students <=0){
        throw new Exception("Null or Negative number of students is invalid.");
    }
    } catch (InputMismatchException e) {
        System.out.print("Invalid input. Please enter a number for student number.");
    } catch (Exception e) {
        System.out.print(e.getMessage());
    }
}

This will catch the both mismatch and negative exceptions.

Although the do... while posted by Siyu Song achieve the desired input from the user, it don't catch negative int exceptions as you wish.

You can use this try and do...while from Siyu Song to achieve what you wanting. The complete code looks like this:

do {
    try {
           System.out.print("Enter the number of students: ");
           students = input.nextInt();
           if(students <=0){
                throw new Exception("Negative number of students is invalid.");
           }
       } catch (InputMismatchException e) {
             System.out.print("Invalid input. Please enter a number for students number.");
       } catch (Exception e) {
              System.out.print(e.getMessage());
     }
     input.nextLine();
} while (students <=0);
Vetchling answered 12/9, 2021 at 19:2 Comment(0)
D
0

You should take the user input inside the try section not outside, and that's how you can solve this problem

Here is an example:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
    
    public static void main(String[] args) {
        
    System.out.println("Enter a number to create table");
    
    Scanner scanner = new Scanner(System.in);
    
    try {
        int userInput = scanner.nextInt();
        
        int i = 0;
        
        while (i<10) {
            
            i++;
            System.out.println(i*userInput);
            
        }
    } catch (InputMismatchException e) {
        System.out.println("Enter a valid number ");
    }
        
    }
}
Discomfit answered 9/4, 2022 at 6:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.