brl214
brl214

Reputation: 537

How to print error if non integer is entered?

The program tells the user whether in integer entered is zero, positive and even or odd, or negative and even or odd.

My issue is I would like to add in a println for an error if a non integer is entered. Look at the last line.

   import java.util.Scanner;

public class IntegerCheck {
  public static void main(String [] args) {

    int x;
    System.out.println("Enter an integer value:");

    Scanner in = new Scanner(System.in);
    x = in.nextInt();
    //String x = in.nextInt();

   if (((x % 2) == 0) && (x< 0))
     System.out.println(x + " is a negative, even integer.");
   else if (((x % 2) == 0) && (x == 0))
  System.out.println(x + " is Zero.");
   else if ((x % 2)==0) 
     System.out.println(x + " is a positive, even integer.");

   if (((x % 2) != 0) && (x<0))
     System.out.println(x + " is a negative, odd integer.");
   else if ((x % 2) != 0)
     System.out.println(x + " is a positive, odd integer.");

   if (x != 'number') 
     System.out.println(x + " is not an integer.");


}
}

Upvotes: 0

Views: 1324

Answers (1)

You can use the InputMismatchException thrown by Scanner.nextInt(). Surround the code in try/catch block and catch a InputMismatchException. It will look something like -

try{
x = in.nextInt();

if (((x % 2) == 0) && (x< 0))
     System.out.println(x + " is a negative, even integer.");
   else if (((x % 2) == 0) && (x == 0))
  System.out.println(x + " is Zero.");
   else if ((x % 2)==0) 
     System.out.println(x + " is a positive, even integer.");

   if (((x % 2) != 0) && (x<0))
     System.out.println(x + " is a negative, odd integer.");
   else if ((x % 2) != 0)
     System.out.println(x + " is a positive, odd integer.");
}
catch(InputMismatchException e){
    System.out.println("You did not enter an integer!");
}

Upvotes: 5

Related Questions