我已经阅读了文件,它应该打印出控制台上的数据,但问题是我收到此错误消息:线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“UNKNOWN”。我把最大长度作为整数,但我怎么把它作为一个字符串呢?
这是我到目前为止所做的:
import java.util.*;
import java.io.*;
public class Task1 {
public static void main(String[] args) {
List<Person> personFile = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("people-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] peopleData = fileRead.split(":");
String commonName = personData[0];
String latinName = personData[1];
int maximumLength = Integer.parseInt(personData[2]);
Person personObj = new Person(commonName, latinName, maximumLength);
personFile.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
System.out.println(personFile);
}
}
人类:
import java.util.*;
public class Person1 {
private String commonName;
private String latinName;
private int maximumLength;
public Person1(String personName, String latinName, int maximumLength) {
this.commonName = personName;
this.latinName = latinName;
this.maximumLength = maximumLength;
}
public String getCommonName() {
return commonName;
}
public String getLatinName() {
return latinName;
}
public int getMaximumLength() {
return maximumLength;
}
@Override
public String toString() {
return null;
}
}
文字档案:
Alisha Khan:Cephaloscyllium ventriosum:100
Jessica Lane:Galeocerdo cuvier:UNKNOWN
Michael Brown:Sphyrna mokarren:600
...
答案 0 :(得分:0)
你应该教你的代码你的UNKNOWN惯例。目前,该代码将其视为数字。
答案 1 :(得分:0)
输入文件中的这一行:
Jessica Lane:Galeocerdo cuvier:UNKNOWN
在您的代码中导致此行出现问题:
int maximumLength = Integer.parseInt(personData[2]);
因为parseInt
会在NumberFormatException
上抛出UNKNOWN
。在这种情况下,您需要决定要做什么。例如,当遇到无效整数时,此代码将maximumLength
保持为默认值:
int maximumLength = -1;
try {
int maximumLength = Integer.parseInt(personData[2]);
} catch (NumberFormatException e) {
}