我正在尝试将文本文件中的文本存储为 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();
}
}
}
每次运行代码时,我都会收到 String ""的 NumberFormatError 错误,就好像程序尝试读取的行中没有任何内容。
文本文件在不同的行上包含值。 EG
7
3
2
1
由于每行都有一些内容,我质疑为什么没有设置变量?
最佳答案
NumberFormatError for String
""
您的文件必须以新的空行结尾。删除它或在 Integer.parseInt 调用之前检查 !currentLine.trim().equals("")
。
关于Java Lang数字格式异常问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33766143/