gpt4 book ai didi

Java Lang 数字格式异常问题

转载 作者:行者123 更新时间:2023-11-30 08:44:26 25 4
gpt4 key购买 nike

我正在尝试将文本文件中的文本存储为 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

因为每一行都有一些东西,我质疑为什么没有设置变量?

最佳答案

NumberFormatError for String ""

您的文件必须以新的空行结束。要么删除它,要么在 Integer.parseInt 调用之前检查 !currentLine.trim().equals("")

关于Java Lang 数字格式异常问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33766143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com