0

The program checks the user input and determines if it's positive or negative. How can I catch the error when the user provides an invalid input (non-integer) such as "444h" or "ibi".

I was thinking the final else statement would catch the exception but it does not.

import java.util.Scanner;
public class Demo

{

    public static void main(String[] args)
    {

        Scanner scan = new Scanner(System.in);
        System.out.print("Enter any number: ");

        int num = scan.nextInt();

        scan.close();
        if(num > 0)
        {
            System.out.println(num+" is positive");
        }
        else if(num < 0)
        {
            System.out.println(num+" is negative");
        }
        else if(num == 0)
        {
            System.out.println(num+" is neither positive nor negative");
        }
        else
        {
            System.out.println(num+" must be an integer");
        }
    }
}

I expect the program to catch the exception and prompt input of a valid integer

2
  • 2
    nextInt only consumes int values Commented Jun 10, 2019 at 9:19
  • 5
    Did you read the documentation for nextInt()? Do you know about exception handling java, try/catch ? Commented Jun 10, 2019 at 9:20

4 Answers 4

3

Simply wrap your code in a try..catch block.

Full code:

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

class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter any number: ");

        try {
            int num = scan.nextInt();
            if (num > 0) {
                System.out.println(num + " is positive");
            } else if (num < 0) {
                System.out.println(num + " is negative");
            } else if (num == 0) {
                System.out.println(num + " is neither positive nor negative");
            }
        } catch (InputMismatchException e) {
            System.out.println("Error: Value Must be an integer");
        }

        scan.close();
    }
}

Good luck :)

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

Comments

1
int num = 0;
    try{
        num =input.nextInt();
    }catch(InputMismatchException ex) {
        System.out.println("Enter Integer Value Only");
    }

You have to write int num = scan.nextInt(); this statement inside try block if you get non-integer value from input then InputMismatchException will arise then catch block will executed.

Comments

1

First off, don't close the Scanner if you plan on using it again during the operation of your application. Once you close it, you will need to restart your application in order to use it again.

As already mentioned, you could utilize a try/catch on the Scanner#nextInt() method:

Scanner scan = new Scanner(System.in);

int num = 0;
boolean isValid = false;
while (!isValid) {
    System.out.print("Enter any number: ");
    try {
        num = scan.nextInt();
        isValid = true;
    }
    catch (InputMismatchException ex) {
        System.out.println("You must supply a integer value");
        isValid = false;
        scan.nextLine(); // Empty buffer
    }
}

if (num > 0) {
    System.out.println(num + " is positive");
}

else if (num < 0) {
    System.out.println(num + " is negative");
}

else if (num == 0) {
    System.out.println(num + " is neither positive nor negative");
}

Or you could use the Scanner#nextLine() method instead which accepts string:

Scanner scan = new Scanner(System.in);

String strgNum = "";
boolean isValid = false;
while (!isValid) {
    System.out.print("Enter any Integer value: ");
    strgNum = scan.nextLine();

    /* See if a signed or unsigned integer value was supplied.
       RegEx is used with the String#matches() method for this.
       Use this RegEx: "-?\\d+(\\.\\d+)?"  if you want to allow
       the User to enter a signed or unsigned Integer, Long, 
       float, or double values.         */
    if (!strgNum.matches("-?\\d+")) {
        System.out.println("You must supply a numerical value (no alpha characters allowed)!");
        continue;
    }
    isValid = true; // set to true so as to exit loop
}
int num = Integer.parseInt(strgNum); // Convert string numerical value to Integer
/* Uncomment the below line if you use the other RegEx. You would have to also 
   comment out the above line as well.   */
// double num = Double.parseDouble(strgNum); // Convert string numerical value to double
if (num > 0) {
    System.out.println(num + " is positive");
}
else if (num < 0) {
    System.out.println(num + " is negative");
}
else if (num == 0) {
    System.out.println(num + " is neither positive nor negative");
}

Comments

0

Use regex to check if input is a number

import java.util.regex.*;
Pattern.matches("[0-9]+", "123"); // this will return a boolean

1 Comment

And how is this suppose to work using Scanner#nextInt()?

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.