gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:20:45 26 4
gpt4 key购买 nike

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

我的问题是我想添加一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com