[英]In Java, how do I check if input is a number?
I am making a simple program that lets you add the results of a race, and how many seconds they used to finish. 我正在制作一个简单的程序,可以让你添加一个比赛的结果,以及他们用完的秒数。 So to enter the time, I did this:
所以为了输入时间,我这样做了:
int time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
So my question is, how can I display an error message to the user if he enters something other than a positive number? 所以我的问题是,如果他输入的数字不是正数,我怎么能向用户显示错误信息? Like a MessageDialog that will give you the error until you enter a number.
就像MessageDialog一样,在输入数字之前会给出错误。
int time;
try {
time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
} catch (NumberFormatException e) {
//error
}
Integer.parseInt
will throw a NumberFormatException
if it can't parse the int
. 如果
Integer.parseInt
无法解析int
则会抛出NumberFormatException
。 If you just want to retry if the input is invalid, wrap it in a while
loop like this: 如果您只想在输入无效时重试,请将其包装在
while
循环中,如下所示:
boolean valid = false;
while (!valid) {
int time;
try {
time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
if (time >= 0) valid = true;
} catch (NumberFormatException e) {
//error
JOptionPane.showConfirmDialog("Error, not a number. Please try again.");
}
}
Integer.parseInt Throws NumberFormatException when the parameter to Integer.parseInt is not a integer, Use try Catch and display required error message, keep it in do while loop as below Integer.parseInt当Integer.parseInt的参数不是整数时抛出NumberFormatException,使用try Catch并显示所需的错误消息,将其保存在do while循环中,如下所示
int time = -1;
do{
try{
time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
}
catch(NumberFormatException e){
}
}while(time<=0);
如果JOptionPane.showInputDialog("Enter seconds")
不是有效数字,您将获得NumberFormatException
。对于正数检查,只需检查time >=0
Depends on how you want to solve it. 取决于你想如何解决它。 An easy way is to declare time as an Integer and just do:
一种简单的方法是将时间声明为整数,然后执行:
Integer time;
while (time == null || time < 0) {
Ints.tryParse(JOptionPane.showInputDialog("Enter seconds"));
}
Of course that would require you to use google guava. 当然,这需要你使用谷歌番石榴。 (which contains a lot of other useful functions).
(其中包含许多其他有用的功能)。
Another way is to use the above code but use the standard tryparse, catch the NumberFormatException and do nothing in the catch. 另一种方法是使用上面的代码,但使用标准的tryparse,捕获NumberFormatException并在catch中不执行任何操作。
There are plenty of ways to solve this issue. 有很多方法可以解决这个问题。
Or not reinvent the wheel and just use: NumberUtils.isNumber
or StringUtils.isNumeric
from Apache Commons Lang
. 或者不重新发明轮子,只需使用:来自
Apache Commons Lang
NumberUtils.isNumber
或StringUtils.isNumeric
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.