如何在Java中检查输入是否为整数?
问题描述:
在我的程序中,我想要用户输入整数。我想要在用户输入非整数值时显示错误消息。
我该怎么做?
我的程序是找到圈子的区域。在哪个用户将输入radius的值。但是如果用户输入一个字符,我想要显示一条消息,说明输入无效。
In my program I want an integer input by the user. I want an error message to be show when user inputs a value which is not an integer. How can I do this. My program is to find area of circle. In which user will input the value of radius. But if user inputs a character I want a message to be shown saying Invalid Input.
这是我的代码:
int radius, area;
Scanner input=new Scanner(System.in);
System.out.println("Enter the radius:\t");
radius=input.nextInt();
area=3.14*radius*radius;
System.out.println("Area of circle:\t"+area);
答
如果您使用扫描仪,你可以这样做:
If you are getting the user input with Scanner
, you can do:
if(yourScanner.hasNextInt()) {
yourNumber = yourScanner.nextInt();
}
如果不是,则必须将其转换为 int
并捕获 NumberFormatException
:
If you are not, you'll have to convert it to int
and catch a NumberFormatException
:
try{
yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
//handle exception here
}