0

嘿,我有问题。我想使用 arrayList 来创建一个 studentStore(我已经完成了),但是当我尝试使用 RandomAccessFile 编写学生时,我一无所知。

StudentStore details = new StudentStore();
Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo@hotmail.com");
Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "fabioborini@gmail.com");
Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "gramirez@webmail.com");
Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "luissuarez@yahoo.com");
Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "carroll123@hotmail.com");

这些是我的学生

现在我需要一种方法将它们写入

RandomAccessFile raf = new RandomAccessFile("employee.dat", "rw");
Student er = new Student(null, null, null, null);
for (int i = 0; i < details.length; i++) //This is getting an error obviously because details wont be taken.  nor will a, b,c , d or e which is what the student was declared at the top.
{
    er.setFirstName([i]);
    er.setLastName(lnames[i]);
    er.setAddress(addresses[i]);
    er.setAge(ages[i]);
    er.setSalary(salaries[i]);
    er.write(raf);
}
raf = new RandomAccessFile("employee.dat", "rw");

er = new Student();

int numRecords = (int) raf.length() / er.size();

for (int i = 0; i < numRecords; i++) {
    er.read(raf);

    System.out.print(er.getStudentName() + " ");
    System.out.print(er.getStudentId() + " ");
    System.out.print(er.getStudentEmail() + " ");
    System.out.print(er.getStudentTelephoneNumber() + " ");
}
raf.seek(0);
for (int i = 0; i < numRecords; i++) {
    er.read(raf);
    if (er.getAge() >= 55) {
        er.setSalary(0.0);
        raf.seek(raf.getFilePointer() - er.size());
        er.write(raf);
        raf.seek(raf.getFilePointer() - er.size());
        er.read(raf);
    }
    System.out.print(er.getStudentName() + " ");
    System.out.print(er.getStudentId() + " ");
    System.out.print(er.getStudentEmail() + " ");
    System.out.print(er.getStudentTelephoneNumber() + " ");
}
4

1 回答 1

2

试试这个StudentStore以获得内部的大小ArrayList

public class StudentStore
{
    ArrayList<Student> students = null;

    public StudentStore()
    {
        students = new ArrayList<Student>();
    }

    public int size()
    {
        return (students == null) ? 0 : students.size();
    }
}

但是,我不明白,为什么您必须创建自己的包装ArrayList而不是使用简单的ArrayList...

于 2012-08-05T11:39:19.500 回答