0

程序告诉用户输入的整数是零、正偶还是奇数、负偶数还是奇数。

我的问题是,如果输入了非整数,我想添加一个 println 以显示错误。看最后一行。

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


}
}
4

1 回答 1

5

您可以使用InputMismatchExceptionthrow by Scanner.nextInt()。将代码包围在try/ catchblock 中并捕获InputMismatchException. 它看起来像 -

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!");
}
于 2013-09-23T22:52:08.627 回答