如果输入非整数,如何打印错误?

时间:2013-09-23 22:48:36

标签: java integer println

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

我的问题是如果输入非整数,我想在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.");


}
}

1 个答案:

答案 0 :(得分:5)

您可以使用InputMismatchException引发的Scanner.nextInt()。围绕try / catch块中的代码并捕获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!");
}