2012-08-05 65 views
0

嘿,我有一個問題。我想使用一個arrayList來創建一個studentStore(我已經完成了這個),但是當我嘗試使用RandomAccessFile來編寫學生時,我很無能。需要一種使用RandomAccessFile從ArrayList存儲區寫入學生的方法

StudentStore details = new StudentStore(); 
Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "[email protected]"); 
Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "[email protected]"); 
Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "[email protected]"); 
Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "[email protected]"); 
Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "[email protected]"); 

這些都是我的學生

,現在我需要一種方法,並寫入到

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() + " "); 
} 
+0

請張貼的具體錯誤。 – Baz 2012-08-05 11:19:12

+0

有什麼問題?請具體說明。 – SiB 2012-08-05 11:20:07

+0

表達式的類型必須是數組類型,但它解析爲Student。這是錯誤。 – Pendo826 2012-08-05 11:20:24

回答

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 ...

+0

我只是習慣於這樣做一家商店。我已經做到了,並要求我在學生而不是學生商店中創建方法。 – Pendo826 2012-08-05 11:43:47

+0

沒關係,我得到了那個工作。 – Pendo826 2012-08-05 11:46:28

+0

@ Pendo826好吧,如果你認爲我有任何幫助,請考慮接受我的答案。否則,請創建自己的答案並接受該答案。 – Baz 2012-08-05 11:47:21

相關問題