我的问题实际上只涉及我应该在哪里放置检查以确保输入是整数的代码位。感谢任何提供帮助的人。
public static String getQuantity(String aQuantity){
while (isValidQuantity(aQuantity)== false ){
errorMessage += "Enter Valid quantityn";
}
return aQuantity;
}
private static boolean isValidQuantity(String aQuantity){
boolean result = false;
try{
Double.parseDouble(aQuantity);
//here?//
result = true;
}catch(Exception ex){
result = false;
}
return result;
}
您可以使用正则表达式轻松完成。对于双重使用,这个:
Pattern.compile("\d+\.\d+")
如果你想照顾科学记数法中的双精度(例如像3.4-e20
(,请使用这个:
Pattern.compile("[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?")
对于整数,您可以简单地使用上述每个正则表达式中.
前面的部分。喜欢
Pattern.compile("\d+")
对于可能有符号的数字,
Pattern.compile("[-+]?[0-9]+")
请注意最后一个末尾的+
。必须至少有一个数字才能成为数字,因此您不能使用 *
,这意味着零或多次出现。
Javadocs for regex here.
在正则表达式中测试双精度的模式。
您的解决方案应该有效,因为任何整数也会解析为双精度值。您可以使其更详细,并让0
表示无效1
表示 int,2
表示双精度。
private static int isValidQuantity(String aQuantity){
int result = 0;
//first try int
try{
Integer.parseInt(aQuantity);
result = 1; //the parse worked
}catch(NumberFormatException ex){
result = 0;
}
if(result == 0)
{
//if it's not an int then try double
try{
Double.parseDouble(aQuantity);
result = 2; //the parse worked
}catch(NumberFormatException ex){
result = 0;
}
}
return result;
}