7

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

     }
 }    
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
John Stef
  • 585
  • 1
  • 4
  • 16
  • 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`. – jlordo May 29 '13 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? – John Stef May 29 '13 at 14:50
  • Easy. Just delete the first 2 lines of code you posted. – jlordo May 29 '13 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 – John Stef May 29 '13 at 14:55
  • No you won't. `students` is an `int`, and they always have a value (default is 0). – jlordo May 29 '13 at 14:57
  • 1
    Error(18,19): variable students might not have been initialized when I run it without the first two lines – John Stef May 29 '13 at 15:01
  • is student `int` or `Integer`? Where you declare it, you can also assign 0 to it... – jlordo May 29 '13 at 15:04
  • the student is int. And the thing is that according to the exercise I have to givei the number of students manually – John Stef May 29 '13 at 15:10
  • What I've said before, plus add `input.nextLine();` to the `catch` block. – jlordo May 29 '13 at 15:17

6 Answers6

10

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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Siyu Song
  • 897
  • 6
  • 21
  • 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 – Jonathan Scialpi Sep 13 '15 at 03:51
  • 2
    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". – Monkeygrinder Dec 04 '15 at 21:09
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();
         }
     } 
stinepike
  • 54,068
  • 14
  • 92
  • 112
  • I have declare it as an int – John Stef May 29 '13 at 14:16
  • 2
    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 http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt(). – Eric Jablow May 29 '13 at 14:21
  • 1
    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 – John Stef May 29 '13 at 14:35
  • have you managed to solve this? if there is any problem you can update the question – stinepike May 29 '13 at 14:37
  • 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. – John Stef May 29 '13 at 14:48
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.

Neeraj
  • 171
  • 2
  • 11
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();
            }
        }
Harun
  • 1
  • 1
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);
calvesmit
  • 11
  • 1
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 ");
    }
        
    }
}
рüффп
  • 5,172
  • 34
  • 67
  • 113