我使用這個功能,找出一個字符串是否是數字找出一個字符串是否是數字的函數拋出
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'是* *可能數字,但它是不** **的整數 –