user3586248
user3586248

Reputation: 163

Java validating Scanner Input with

How would I use InputMismatchException to determine if the value entered into the Scanner is not an integer? Basically, if they enter in a word instead of an integer I need to use InputMismatchException to return a message.

while (true) {

        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt();
        try{
            Integer.parseInt(i);
        } catch (InputMismatchException e) {
            System.out.println("Sorry, " + i + " is not a number.");
        }

        if (i == 1) {
            System.out.println("1 was selected");
        } else {
            System.out.println("1 was not selected");

        }

Upvotes: 3

Views: 70

Answers (3)

Chinna
Chinna

Reputation: 1

I am new to the programming, I think I got the code for your question.

while (true) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        try{
           int i = Integer.parseInt(s);
           if (i == parseInt(i, 3)) {
               System.out.println(s+" is selected");
           } else {
               System.out.println("Input value is " + s);
           }
        } catch (NumberFormatException e) {
            System.out.println("Sorry, " + s + " is not a number.");
        }}}
        private static int parseInt(int i, int j) {
        // TODO Auto-generated method stub
        return 0;
    }}

reference

Upvotes: 0

billjamesdev
billjamesdev

Reputation: 14640

Change your code as such:

while (true) {
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    try{
       int i = Integer.parseInt(s);

       if (i == 1) {
           System.out.println("1 was selected");
       } else {
           System.out.println("1 was not selected");
       }
    } catch (NumberFormatException e) {
        System.out.println("Sorry, " + s + " is not a number.");
    }


}

Changes:

  • Note use of nextLine(). This is because it seems you want to use the input as part of your error message, and nextInt() won't let you do that.
  • We can now move the i declaration inside the try block, along with the code that uses it, so we won't issue "1 was not selected" when the input was "ssss" or whatever.
  • We use NumberFormatException, as that's what Integer.parseInt() throws when it can't parse an integer from the String.

Upvotes: 2

3kings
3kings

Reputation: 838

This is what i mean

while (true) {

    Scanner sc = new Scanner(System.in);
    int i = -1;
    try
    {
        i = sc.nextInt();
    } 
    catch (InputMismatchException e)
    {System.out.println("Sorry, " + i + " is not a number.");}

    if (i == 1)
        System.out.println("1 was selected");
    else
        System.out.println("1 was not selected");
}

Upvotes: 0

Related Questions