簡體   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