如何修复ArrayList的输出?

时间:2013-08-10 02:58:43

标签: java arrays algorithm arraylist

我正在编写一个从文件中读取的程序。文件中的每一行都包含有关学生的信息。每个学生都由“学生”类中的对象表示。类Student有一个方法getName,它返回学生的名字。通过该文件返回的方法和包含学生对象的ArrayList。我的问题是,每次我使用for循环访问ArrayList并获取每个学生的名字时,我得到的是列表中最后一个学生的名字。通过该文件的方法称为“FileAnalyzer”以下是我的代码。

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class StudentStats {

public static void main(String[] args) {

    List<Student> example = null;
    example = FileAnalyzer("C:\\Users\\achraf\\Desktop\\ach.csv");

    for ( int i = 0; i < example.size(); i++)
    {
        System.out.println(example.get(i).getName());
    }

}

public static List<Student> FileAnalyzer(String path) //path is the path to the file
{ 
    BufferedReader br = null;
    List<Student> info = new ArrayList<Student>();
    String line = "";

    try {
        br = new BufferedReader (new FileReader(path));

        while ((line = br.readLine()) != null)
        {
            //We create an object "Student" and add it to the list

            info.add(new Student(line));

        }

        }

    catch (FileNotFoundException e) {
        System.out.println("Aucun fichier trouvé");
    } catch (IOException e) {
        e.printStackTrace();
    }

    finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    return info;
}

如果您需要它,这里是班级学生的代码

// This class create objects for each student

public class Student {

    private static String Name ="";
    private static String Sex = "";
    private static String Grade = "";

    //constructor
    public Student(String infos)
    {
        String [] etudiant = infos.split(",");

        Name = etudiant[0];
        Sex = etudiant[1];
        Grade = etudiant[2];            
    }

    // Getter functions

    public String getName()
    {
        return Name;
    }
    public String getSex()
    {
        return Sex;
    }
    public String getGrade()
    {
        return Grade;
    }

}

以下是程序读取的典型文件的内容。

lovett,M,12
Achos,F,23
Loba,M,24

真正的问题是,在运行我的代码获取名称后,我得到名称“Loba”三次而不是获得所有名称。

2 个答案:

答案 0 :(得分:3)

以下是Student课程中的问题:

private static String Name ="";
private static String Sex = "";
private static String Grade = "";

您需要从成员变量中删除static,否则所有对象将共享相同的属性,因此您只会看到在这些变量中写入的最后一个值。

在此处详细了解实例和类变量:http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

答案 1 :(得分:2)

您的成员变量在Student类中声明为static。这意味着它们在整个程序中作为一个副本存在,而不是每个实例的一个副本,这是您想要的。每当您创建新学生时,您都会将姓名,性别和成绩设置为新的,但这些值与任何特定学生无关。所有学生都共享这些属性,并且它们在文件读取循环中被覆盖,因此文件中的姓氏将是静态变量的名称。