我正在尝试将文本文件中的文本存储为Java程序中的变量。
源代码如下:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* Write a description of class Reader here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Reader
{
// instance variables - replace the example below with your own
private int areaNumber;
private int studyPeriod;
private int rentalCharges;
private int CAPEX;
private int OPEX;
private double interestRate;
private int[] rolloutPlanPerArea;
private int householdsPerArea;
private double adoptionRatePerArea;
private String fileName = "practical6a.txt";
public void run(){
load(fileName);
}
private void load(String fileName){
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String currentLine = null;
while ((currentLine = reader.readLine()) != null) {
areaNumber = Integer.parseInt(currentLine.trim());
studyPeriod = Integer.parseInt(currentLine.trim());
rentalCharges = Integer.parseInt(currentLine.trim());
CAPEX = Integer.parseInt(currentLine.trim());
OPEX = Integer.parseInt(currentLine.trim());
interestRate = Integer.parseInt(currentLine.trim());
}
reader.close();
System.out.print(areaNumber);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
每次代码运行时,我都会得到一个字符串“”的NumberFormatError,好像程序试图读取的行没有任何内容。
文本文件包含单独行的值。 EG
7
3
2
1
由于每行都有一些内容我会质疑为什么没有设置变量?
答案 0 :(得分:2)
字符串
的NumberFormatError!currentLine.trim().equals("")
您的文件必须以新的空行结束。在Integer.parseInt调用之前删除它或检查{{1}}。
答案 1 :(得分:0)
检查String是否为空
a,(b,(c,d)) = [1,[2,[3,4]]]