List.Add意外地在Java中多次添加相同的东西

时间:2014-11-23 00:16:25

标签: java list file arraylist

我是一个刚开始学习集合的完整Java新手。我试图编写一个可以获取文本文件并从该文件内容创建对象列表的程序。具体来说,我有一个班级学生,每个学生都有名字,姓氏和毕业年份。我使用的文本文件格式为:

Tom Blue 2007 理查德格林1996 Robert Black 2003 贝丝怀特2005年

除了每个学生之间有新的界限。我得到的问题是,当我去创建我的列表时,它似乎创建了一个列表,其中包含我的列表中最后一个学生的多个实例。例如,如果我使用上面四个学生的文件,我的程序会创建一个包含4份Beth White 2005副本的列表。我不完全确定我在这里做错了什么......我不是&# 39;认为我的扫描仪存在问题,而且我确定我的打印方法没有问题,因为我使用了默认的打印方法并且发生了同样的结果。这是我的代码:

import java.io.IOException;
import java.lang.IllegalStateException;
import java.nio.file.*;
import java.util.*;

public class StudentList
{
private static Scanner input;

public static void main(String[] args)
{
    Scanner keyInput = new Scanner(System.in);

    System.out.println("Please enter the name of the file containing the students.");
    String fileName = keyInput.next();

    List<Student> studentList = new ArrayList<>(openAndReadFile(fileName));
    printList(studentList);
}

private static List<Student> openAndReadFile(String fileName)
{
    try
    {
        input = new Scanner(Paths.get(fileName));
    }
    catch (IOException ioException)
    {
        System.err.println("Error opening file.  Terminating.");
        System.exit(1);
    }

    List<Student> studentList = new ArrayList<>();

    try
    {
        while (input.hasNext())
        {
            studentList.add(new Student(input.next(), input.next(), input.nextInt()));
        }
    }
    catch (NoSuchElementException ee)
    {
        System.err.println("File improperly formed.  Terminating.");
    }
    catch (IllegalStateException se)
    {
        System.err.println("Error reading from file.  Terminating.");
    }

    if (input != null)
        input.close();

    return studentList;
}

private static void printList(List<Student> list)
{
    for (Student student : list)
        System.out.printf("%s%n", student);
}
}

1 个答案:

答案 0 :(得分:2)

班级Student是否有机会使用static字段?

使用static字段将导致为该类的所有实例(即分配的最后一个实例)为每个字段分配一个可能的值。如果是这种情况,请删除static关键字,以便类字段对应于Student的每个实例