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

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


}
}

最佳答案

您可以使用由 Scanner.nextInt() 抛出的 InputMismatchException。将代码包围在 try/catch block 中并捕获 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!");
}

关于java - 如果输入非整数如何打印错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18970173/

相关文章:

java - 奇怪的java打印输出

java - java Math.random() 生成 1 到 2 之间的数字,并为每个数字设置概率

java - 在方法参数内声明变量

java - 打印形成

vb.net - 检查字符串变量是否具有整数值

Python 类型错误 : an integer is required while working with Sockets

c# - 当我只能在 C# 中使用 float 或 double 时,为什么我应该使用整数?

java - REST 服务和 Servlet

java - 这两个任务是同时执行的吗?

java - 选项菜单无法覆盖?