【发布时间】:2016-08-12 03:28:36
【问题描述】:
当我尝试从文本文件中读取一些数据并将其转换为整数时,我收到了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);
}
我知道我的代码可能真的很草率而且效率低下......我有点菜鸟。
【问题讨论】:
-
在通过之前尝试
holderStr.trim(),你为什么要再次投射到 Double ?你的字符串中可能还有一些额外的字符,所以这些可能是NumberFormatException的原因 -
只是为了清楚变量“totalBalNum”是整数还是双精度数?
-
能否提供异常的Stacktrace?
-
@Deepak totalBalNum 是双精度数。我已经对此进行了试验,并将其转换为双精度不会导致错误。修剪字符串也不起作用。
标签: java filereader numberformatexception