【发布时间】:2019-05-16 12:12:59
【问题描述】:
我一直在尝试创建一个从具有 3 条记录(姓名、年龄)的文本文件中读取的方法
在我的课程中,我包括 getter setter compareTo 和 toString 方法。
马克·道格,21 岁
大卫·布拉夫,19 岁
马克·伊登,17 岁
我得到的错误是:
Exception in thread "main" java.lang.NumberFormatException: For input string: " 28"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at lab7.People.readPersons(People.java:44)
at lab7.People.main(People.java:63)
该方法必须将名称与年龄分开(已经完成) 并打印数组列表
public static List<People> readPersons(String fileName) throws FileNotFoundException{
Scanner sc= new Scanner(new File(fileName));
List <People> persons= new ArrayList<>();
while (sc.hasNext()) {
String line = sc.nextLine();
String[] alo = line.split(",");
int age = Integer.parseInt(alo[1]);
String name = alo[0];
persons.add(new People(name, age));
}
return persons;
}
@Override
public String toString() {
return "name " +getName()+"age " +getAge();
}
public static void main(String[] args) throws FileNotFoundException {
System.out.println(readPersons("C:\\Users\\Mark \\Desktop\\CS\\JAVA\\exersice\\src\\Person\\data"));
我从“data.txt”文件中复制了目录(与我的 Person 类在同一个包中 不幸的是,我遇到了一个我不知道为什么的错误。
【问题讨论】:
-
您可以粘贴您在这样做时遇到的错误吗?
-
@SidharthaShankar 完成
-
错误信息非常具体,甚至包括无效输入。
-
@Arnaud 你在我的代码中看到任何地方寻求关于拆分的帮助吗?
-
@JohnMichael:你读过链接的问题吗?您的问题是拆分后令牌中的剩余空格:
" 28"不是解析为数字的有效字符串,"28"是。
标签: java