【发布时间】:2019-06-10 09:17:34
【问题描述】:
程序检查用户输入并确定它是正面的还是负面的。 当用户提供无效输入(非整数)(例如“444h”或“ibi”)时,如何捕获错误。
我在想最后的 else 语句会捕获异常,但它没有。
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = scan.nextInt();
scan.close();
if(num > 0)
{
System.out.println(num+" is positive");
}
else if(num < 0)
{
System.out.println(num+" is negative");
}
else if(num == 0)
{
System.out.println(num+" is neither positive nor negative");
}
else
{
System.out.println(num+" must be an integer");
}
}
}
我希望程序能够捕获异常并提示输入有效整数
【问题讨论】:
-
nextInt 只消耗 int 值
-
您是否阅读了
nextInt()的文档?你知道java异常处理吗,try/catch?
标签: java