0

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


}
}

1 Answer 1

5

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!");
}
Sign up to request clarification or add additional context in comments.

Comments

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.