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");

     }
 }    
9
  • 1
    The first students = input.nextInt(); is not inside the try block and your entering something that can't be stored in a an int. Commented May 29, 2013 at 14:22
  • 1
    Yes it seems that this is the case but how can I check for both (letter and negative numbers exception) together? Commented May 29, 2013 at 14:50
  • Easy. Just delete the first 2 lines of code you posted. Commented May 29, 2013 at 14:51
  • 1
    If I delete the first two lines then I will get an error in the while loop because the students wont have a value Commented May 29, 2013 at 14:55
  • 1
    Error(18,19): variable students might not have been initialized when I run it without the first two lines Commented May 29, 2013 at 15:01

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 compilation
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".
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();
         }
     } 

5 Comments

I have declare it as an int
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/….
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 break
have you managed to solve this? if there is any problem you can update the question
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.
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.

Comments

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();
            }
        }

Comments

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

Comments

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 ");
    }
        
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.