我正在尝试从包含多行“name,int month,int date,int year”信息的文件中读取数据。 Person对象将这些项作为其构造函数参数。但是,当我尝试从文件中读取并填充列表时,我收到以下错误:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at lab03.PersonSort.populate(PersonSort.java:56)
at lab03.PersonSort.main(PersonSort.java:38)
这是我的代码:
public static void main(String[] args) throws Exception {
ArrayList<Person> people = new ArrayList<Person>();
populate(people);
//selectionSort(people);
int index = 0;
while (index < people.size())
{
System.out.println(people.get(index));
index++;
}
}
public static ArrayList populate(ArrayList<Person> array) {
final String PERSON_FILE = ".\\src\\Persons.txt";
Scanner input = new Scanner(PERSON_FILE);
while (input.hasNext()) {
String name = input.next();
int month = input.nextInt();
int day = input.nextInt();
int year = input.nextInt();
Person temp = new Person(name, month, day, year);
array.add(temp);
}
return array;
}
persons.txt文件包含以下内容:
Merli 9 10 1998
Elijah 3 19 2013
Christine 7 29 1981
Annie 8 28 2002
Bella 8 28 2010
马特9 11 1952
Cassidy 8 5 1997
答案 0 :(得分:0)
原因是您正在尝试解析字符串&#34;。\\ src \\ Persons.txt&#34;而不是文件的内容。写Scanner input = new Scanner(new File(PERSON_FILE).toPath());
应该解决它。