我使用这个功能,找出一个字符串是否是数字找出一个字符串是否是数字的函数抛出
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;
}
目的是使用户可以引入各种样imputs的。只要它们不是数字或整数数字,程序就会再次要求引入数字,但不会像现在这样发生。任何想法?
跟踪告诉你它在parseInt函数崩溃,因为它期望一个int。要么尝试接听电话,要么确保您的号码是一个整数。 –
解决方案是实现另一个功能,以确定Sting的数量与否。通过这种方式:公共静态布尔esNumero(String s)将 \t \t { \t \t尝试\t \t \t { \t \t \t的Integer.parseInt(S); \t \t \t return true; \t \t \t} 赶上(NumberFormatException的五){返回false;} } – heptagono
'98,8'是* *可能数字,但它是不** **的整数 –