我创建了一个 Person 类,带有参数 firstname、lastname 和 year。我需要弄清楚如何从文本文件中读取输入并创建一个人员数组。这是我正在尝试的,基于我从网络上收集的不同来源。
String name = "People.txt";
Person[] people = new ArrayList<Person>();
BufferedReader br = new BufferedReader(new FileReader(name));
String line = br.readLine();
while(line != null)
{
people.add(line);
line = br.readLine();
}
但是,当然,这是行不通的。我怀疑它甚至接近正确,所以我想知道你们是否有任何建议。
另外,我的 Person 类的构造函数如下:
public Person(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
The error reads,
`SortingImplementation.java:15: incompatible types
found : java.util.ArrayList<Person>
required: Person[]
Person[] people = new ArrayList<Person>();
^
SortingImplementation.java:20: cannot find symbol
symbol : method add(java.lang.String)
location: class Person[]
people.add(line);
^
Note: SortingMethod.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors
`
文本文件是
Larry Kim 45
Bob Stuart 51
Nancy Davis 38
John Doe 49
Henry Miles 23
Albert Lee 36
Mary Wing 43
Tony Rich 55
Ally Sneetch 19
Carrie Chrome 77
David Abkenzy 41
Young Old 18
Snow White 70
George Herald 60
Mike Bush 22
Peter Paul 33
Peter Pan 44
Mary Paul 25
Ray Romano 55
嗯,甜的。你们太棒了,也许我今晚要睡觉了。已经连续两天试图完成这项工作,开始产生幻觉。我遇到的最后一个问题,我相信这很简单,但我收到了这个错误。
SortingImplementation.java:15: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
BufferedReader br = new BufferedReader(new FileReader("People.txt"));
^
SortingImplementation.java:16: unreported exception java.io.IOException; must be caught or declared to be thrown
String line = br.readLine();
我认为这可能与我实例化的方式有关,或者我没有导入正确的头文件。这是我导入的内容。
import javax.swing.JOptionPane;
import java.util.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.io.*;
import java.nio.*;
你们有没有看到什么可能丢失的东西?