Java 查找字符串是否为数字的函数引发异常
我使用这个函数来确定字符串是否是数字Java 查找字符串是否为数字的函数引发异常,java,input,Java,Input,我使用这个函数来确定字符串是否是数字 public static boolean esNumerico(String s) { return s.matches("[-+]?\\d*\\,?\\d+"); } 当程序启动时,它要求用户输入一个数字。 如果我引入数字88,99,它会崩溃: Exception in thread "main" java.lang.NumberFormatException: For input string: "98,8" at jav
public static boolean esNumerico(String s) {
return s.matches("[-+]?\\d*\\,?\\d+");
}
当程序启动时,它要求用户输入一个数字。
如果我引入数字88,99,它会崩溃:
Exception in thread "main" java.lang.NumberFormatException: For input string: "98,8"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at actividad03.Ejercicio01.pideEntero(Ejercicio01.java:32)
at actividad03.Ejercicio01.main(Ejercicio01.java:14)
完整的功能代码为:
static int pideEntero(){
int number1;
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String str = null;
try{
do {
System.out.println("Introduzca un número entero:");
str = br.readLine(); //Toma una línea y la almacena como String
} while (esNumerico(str)==false);
}
catch(Exception e)
{System.out.println("Dato no válido.");
}
number1=Integer.parseInt(str);
System.out.println("Valor numérico correcto!");
//number1=Integer.parseInt(str);
return number1;
}
目的是用户可以引入各种输入。当它们不是数字或整数时,程序将再次要求引入数字,但不会像现在这样崩溃。有什么想法吗?下面的一行出现了崩溃,因为您无法将逗号分隔的字符串文字转换为整数
number1=Integer.parseInt(str);
你可能想这样做
number1 = Integer.parseInt(str.replaceAll(",", ""));
也许有一个更简单的方法来处理你的问题。您可以尝试直接将输入解析为double,然后确保没有抛出任何
NumberFormatException
。大概是这样的:
double number1;
do {
System.out.println("Introduzca un número entero:");
try {
str = br.readLine();
number1 = Double.parseDouble(str);
// with a valid input in hand, we can now break and leave the loop
break;
} catch (NumberFormatException e) {
System.out.println("El numero es inválido, introduzca otra vez:");
} catch (Exception e) {
System.out.println("Otro problema, introduzca otra vez:");
}
} while (esNumerico(str) == false);
实际上,这可能是正确的做法,因为我们让Java确定什么是有效的字符串数字,什么不是有效的字符串数字,而不是试图使用正则表达式猜测自己
如果你必须继续你目前的方法,那么继续阅读。您的代码出现问题,因为它正在验证双精度输入,而不是整数,但您正试图通过以下方式将验证后的输入解析为整数:
number1 = Integer.parseInt(str);
相反,如果数字通过验证,则使用以下代码作为双精度解析:
NumberFormat format = NumberFormat.getInstance(new Locale("es", "ES"));
Number number = format.parse(str);
double d = number.doubleValue();
用于验证的正则表达式也有一个问题,因为像+98,8
这样的数字不能正确解析为double(尽管-99,8
会)。请尝试使用此选项:
public static boolean esNumerico(String s) {
return s.matches("[-]?\\d+(,\\d+)?");
}
正则表达式的解释:
[-]? match an optional leading minus sign
\\d+ followed by one or more digits
(,\\d+)? followed by an optional comma, and then one or more digits
如果希望允许前导加号,则修改正则表达式,但请注意,在将字符串解析为双精度之前,必须先删除它。下面的一行抛出错误
number1=Integer.parseInt(str);
新的解决方案:
public static boolean esNumero (String s)
{
try
{
Integer.parseInt(s);
return true;
}
catch (NumberFormatException e){return false;}
}
Integer.parseInt()在某些国家/地区不支持用于分隔数字的逗号。相反,可以使用DecimalFormat,这确实允许这样做
NumberFormat format = new DecimalFormat();
System.out.println(format.parse("12,34").intValue());
输出
8899
注意:DecimalFormat取决于语言环境,在我的当前位置,我的本地语言恰好是en_GB,这意味着默认情况下groupingUsed标志处于启用状态。你可以通过调用
format.setGroupingUsed(true);
当输入无效时,NumberFormat实例将出现异常,因此这也可用于验证您的数字
try {
System.out.println(format.parse("88,99").intValue());
} catch (ParseException e) {
// do something else
}
跟踪告诉您它在parseInt中崩溃,因为它需要一个int。请尝试捕获调用,或者首先确保您的号码是int。解决方案是实现另一个函数,以确定Sting在多大程度上是数字。这样:公共静态布尔esNumero(字符串s){try{Integer.parseInt(s);return true;}catch(NumberFormatException e){return false;}}
98,8
可能是数字,但不是整数