如何在Java中检查输入是否为整数? [英] How to check the input is an integer or not in Java?

查看:783
本文介绍了如何在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);


推荐答案

如果您使用<$ c获取用户输入$ c>扫描仪,你可以这样做:

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
}

这篇关于如何在Java中检查输入是否为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆