程序告诉用户输入的整数是否为零、正偶或奇数、或负数或偶数或奇数。
我的问题是我想添加一个 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/