从java

时间:2016-05-01 23:59:10

标签: 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;
    }
}

3 个答案:

答案 0 :(得分:1)

使用拆分功能

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对象中的split函数将拆分包含空白空间的任何子字符串,如上例所示。您可以选择拆分例如逗号&#34;,&#34;在使用String[] student = line.split(",");的CSV文件中但在这种情况下它是空的空间。 Split将返回一个字符串数组

答案 1 :(得分:1)

类似的东西:

rescue_from ActiveRecord::RecordNotUnique, with: :record_not_unique

    def record_not_unique
      render json: {errors: {message: 'Record not unique.'}}, status: :accepted
    end

答案 2 :(得分:0)

应该工作:

bootstrap.yml