1


I defined a function readInt() which returns an int (based on Scanner.nextInt()).

The problem is: if I enter a character, I get this exception: (java.util.InputMismatchException).

I've tried to fix it without success using a try-catch block.

What's wrong?

public static int readInt(String message, int min, int max)
{
    displayBlack(message);
    int number = scanner.nextInt();

    try{
        if (number < min || number > max)
        {
            return readInt("Erreur, Selectionner un nombre entre " + min + " et " + max, min, max);
        } else
        {
            return number;
        }
    }
    catch (NumberFormatException e){
            return readInt(message, min, max);
    }
}



EDIT :

I changed my function to :

public static int readInt(String message, int min, int max)
{
    displayBlack(message);

    try{
        String result = scanner.next();
        int number = Integer.parseInt(result);

        if (number < min || number > max)
        {
            return readInt("Erreur, Selectionner un nombre entre " + min + " et " + max, min, max);
        } else
        {
            return number;
        }
    }
    catch (Exception e){
            return readInt("Erreur, Selectionner un nombre entre " + min + " et " + max, min, max);
    }
}

Now it's working. Is it a good way or a dirty hack?

Machado
  • 14,105
  • 13
  • 56
  • 97
YoannLth
  • 197
  • 2
  • 14
  • 1
    Have you looked at `hasNextInt`? It's not clear what you expect `return readInt("Erreur, ...")` to do... – Jon Skeet Jan 19 '16 at 17:43
  • 2
    You should also handle InputMismatchException – Pankaj Pandey Jan 19 '16 at 17:45
  • 1
    If you catch an exception that way, you're just going to recursively catch infinite exceptions until you get a stack overflow. At the very least, you need to change the inputs so that the successive call to the method doesn't do the exact same thing that caused the exception in the first place. – Mage Xy Jan 19 '16 at 17:47
  • Do you know which line is throwing this exception? – Mohit Sharma Jan 19 '16 at 18:05

3 Answers3

1

I believe you are misunderstanding where the error is coming from. Your try/catch seems like it is catching out of bounds errors (e.g. Too large to be an int or too small) however ignores the scanner.nextInt() which I assume is where the error is. Try putting it in a try/catch like this and playing with it until you get the correct results.

displayBlack(message);
try {
    int number = scanner.nextInt();
} catch(Exception e) { //Just using this as a catch all - you might want to be more specific.
    ...
Sh4d0wsPlyr
  • 948
  • 12
  • 28
  • 2
    Related: [Why is the `catch(Exception)` almost always a bad Idea?](https://stackoverflow.com/q/2416316) – Siguza Jan 19 '16 at 17:47
  • Although I certainly agree with you @Siguza, I am using that as a catch all since I do not know how the question wants to handle each. In fact I noted it already (7 seconds before you posted) that they should be more specific. :) – Sh4d0wsPlyr Jan 19 '16 at 17:49
  • I didn't mean to correct you, I just wanted to provide information for anyone reading this as to why they should bother. :) – Siguza Jan 19 '16 at 17:53
0

I've modified your code a bit.

public static Integer readInt(String message, int min, int max)
{
    /*displayBlack(message);*/

    try {
        /*String result = scanner.next();*/
        int number = Integer.parseInt(message);

        if (number < min || number > max) {
            System.out.println("Erreur, Selectionner un nombre entre " + min + " et " + max);
            /*return readInt();*/
        }
        return number;
    } catch (InputMismatchException e) {
        System.out.println("You must enter a number: " + e.toString());
        return null;
    } catch (NumberFormatException e) {
        System.out.println("You must enter a number: " + e.toString());
        return null;
    } catch (Exception e) {
        System.out.println("Another problem:" + e.toString());
        return null;
    }
}

I made readInt return an Integer (which can be a null in case the number is invalid).

I commented out the scanner.next statement, because you seem to be passing it in through message.

The return statement can only return an object of the type declared in your method signature. Since you declared it an int, it can only return an int. I declared it an Integer so it could return an int or a null. Note that it can't return a String, as you had.

I added two more catches before the broadest Exception, namely InputMismatchException and NumberFormatException.

I tested it with these two statements:

    Integer test = StackoverflowApplication.readInt("42", 0, 10);
    Integer readMe = StackoverflowApplication.readInt("c", 0, 10);

It returns a 42 for the first (while printing out the "Erreur" message) and a null for the second. Mine throws a NumberFormatException.

rajah9
  • 11,645
  • 5
  • 44
  • 57
-1

You are getting InputMismatchException because you used nextInt() of Scanner which only accepts integer while you are giving character. If you want to accept string argument then you have to try for next() or something else. Hope it helps you...

pratapvaibhav19
  • 222
  • 2
  • 12