繁体   English   中英

从Java中输入的文本文件在ArrayList中创建对象

[英]Create object in an ArrayList from textfile input in java

我有一个学生列表的文本文件,其中列出了姓,名,实验室等级,项目等级和考试等级,例如:

Owens Will 46 54 56  
Smith John 44 77 99

我正在尝试编写一种方法,该方法读取文本文件,使用每一行创建一个Student对象,然后将其添加到Student的ArrayList中。 Student对象由名字,姓氏,实验室,项目和考试成绩组成。

这是我到目前为止的内容:

private ArrayList<Student> arraylist = new ArrayList<Student>();

public void ReadFile(String inputfile) throws FileNotFoundException {
    File myFile = new File(inputfile);
    Scanner sc = new Scanner(myFile);

    while (sc.hasNextLine()) {
        arraylist.add(sc.nextLine());
    }
}

我不确定如何从文本文件创建Student对象,然后不确定如何将对象放入ArrayList?

编辑:

这是我的学生班:

public class Student {
    // fields
    private String firstname;
    private String lastname;
    private int labgrade;
    private int projectgrade;
    private int examgrade;
    private int totalgrade;

    // constructor
    public Student(String firstname, String lastname, int labgrade,
        int projectgrade, int examgrade) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.labgrade = labgrade;
        this.examgrade = examgrade;
        this.totalgrade = labgrade + projectgrade + examgrade;
    }

    // method
    public String toString() {
        String s = firstname + " " + lastname + " has a total grade of "  + totalgrade;
        return s;
    }
}

使用分割功能

String line = sc.nextLine();
String[] student = line.split(" ");
String lastName = student[0];
String firstName = student[1];
String labGrade = student[2];
String projectGrade = student[3];
String examGrade = student[4];

new Student(student[0],student[1],student[2],student[3],student[4]) ,在String对象中拆分的函数将拆分任何包含空白的子字符串,如上面的示例。 您可以选择使用String[] student = line.split(",");在CSV文件中拆分例如逗号“,”,而String[] student = line.split(","); 但在这种情况下,它是空白空间。 拆分将返回字符串数组

就像是:

public void ReadFile(String inputfile) throws FileNotFoundException {
    arraylist = new ArrayList<Student>();
    File myFile = new File(inputfile);
    Scanner sc = new Scanner(myFile);

    while (sc.hasNextLine()) {
        try {
            String[] line = sc.nextLine().split(" ");

            arraylist.add(new Student(line[1], line[0], Integer.parseInt(line[2]), ...));
        } catch (Exception e) {
            System.out.println("Error of some kind...");
            continue; // maybe, I dunno.
        }
    }
}

应该管用:

private ArrayList<Student> arraylist = new ArrayList<Student>();

public void ReadFile(String inputfile) throws FileNotFoundException 
{
    File myFile = new File(inputfile);
    Scanner sc = new Scanner(myFile);

    while (sc.hasNextLine()) 
    {
        String[] stdinfo = sc.nextLine().split(" ");
        arraylist.add(new Student(stdinfo[1], stdinfo[0], Integer.parseInt(stdinfo[2]), Integer.parseInt(stdinfo[3]), Integer.parseInt(stdinfo[4])));
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM