读取文件时出现 NumberFormatException 错误
NumberFormatException error from reading a file
当我尝试从文本文件中读取一些数据并将其转换为整数时,出现 NumberFormatException
错误。从我看到其他人的说法来看,这个错误是在使用 pasreInt()
将空字符串转换为整数时引起的。但我已经能够将文件中的字符串“1”打印到输出中。有谁知道为什么即使字符串似乎不为空我也会收到此错误?这是我的代码:
try {
//Retrieve Info
FileReader fr = new FileReader("BankInfo.txt");
BufferedReader br = new BufferedReader(fr);
//Skip specified number of lines
for(int i=0; i<line; i++) {
br.readLine();
}
//Print the string to output
String holderStr = br.readLine();
System.out.println(holderStr);
//The line creating the NumberFormatException
totalBalNum = (double)Integer.parseInt(holderStr);
br.close();
//Read Whole File
BufferedReader br2 = new BufferedReader(fr);
while((str = br.readLine()) != null) {
arrList.add(str);
}
br2.close();
} catch (IOException | NumberFormatException e) {
System.out.println("ERROR! Problem with FileReader. " + e);
}
我知道我的代码可能也很草率和低效...我有点菜鸟。
好的,我认为将字符串转换为整数然后将其类型转换为双精度是导致错误的原因。为什么不将字符串转换为 double。
此外,您在阅读时必须 trim 该行以避免任何空格。
String holderStr = br.readLine().trim();
System.out.println(holderStr);
totalBalNum = Double.parseDouble(holderStr);
使用replaceAll()
将除数字以外的所有字符转换为空字符。
holderStr.replaceAll("\D+","");
例如
字符串 extra34345 dfdf
将被转换为 34345
字符串 ab34345ba
将被转换为 34345
字符串 \n34345\n
将被转换为 34345
代码
String holderStr = br.readLine();
//this line will remove everything from the String, other than Digits
holderStr= holderStr.replaceAll("\D+","");
System.out.println(holderStr);
当我尝试从文本文件中读取一些数据并将其转换为整数时,出现 NumberFormatException
错误。从我看到其他人的说法来看,这个错误是在使用 pasreInt()
将空字符串转换为整数时引起的。但我已经能够将文件中的字符串“1”打印到输出中。有谁知道为什么即使字符串似乎不为空我也会收到此错误?这是我的代码:
try {
//Retrieve Info
FileReader fr = new FileReader("BankInfo.txt");
BufferedReader br = new BufferedReader(fr);
//Skip specified number of lines
for(int i=0; i<line; i++) {
br.readLine();
}
//Print the string to output
String holderStr = br.readLine();
System.out.println(holderStr);
//The line creating the NumberFormatException
totalBalNum = (double)Integer.parseInt(holderStr);
br.close();
//Read Whole File
BufferedReader br2 = new BufferedReader(fr);
while((str = br.readLine()) != null) {
arrList.add(str);
}
br2.close();
} catch (IOException | NumberFormatException e) {
System.out.println("ERROR! Problem with FileReader. " + e);
}
我知道我的代码可能也很草率和低效...我有点菜鸟。
好的,我认为将字符串转换为整数然后将其类型转换为双精度是导致错误的原因。为什么不将字符串转换为 double。 此外,您在阅读时必须 trim 该行以避免任何空格。
String holderStr = br.readLine().trim();
System.out.println(holderStr);
totalBalNum = Double.parseDouble(holderStr);
使用replaceAll()
将除数字以外的所有字符转换为空字符。
holderStr.replaceAll("\D+","");
例如
字符串 extra34345 dfdf
将被转换为 34345
字符串 ab34345ba
将被转换为 34345
字符串 \n34345\n
将被转换为 34345
代码
String holderStr = br.readLine();
//this line will remove everything from the String, other than Digits
holderStr= holderStr.replaceAll("\D+","");
System.out.println(holderStr);