尝试使用Array实现saveData()和deleteData()

时间:2014-09-05 18:53:32

标签: java

SaveData()deleteData()位于我的studentList类中。我试图在我的UI中调用它们,但它们没有按预期工作。

我也有学生班。有什么好主意吗?

// This is in my UI for my Save and delete button
        //add actionListener to SaveData
         saveData.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e) {
                 theList.saveData();
             }
         });


         //add actionListener to DeleteData

         deleteData.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e) {
                 theList.deleteData();
             }
         });
//saveData()in the StudentList Class

 public void saveData() {
        try {
            FileOutputStream fileOut = new FileOutputStream("StudentData.dat");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeInt(numberOfStudents);

            writeStudentsToFile(out);
            out.close();
            fileOut.close();
        } catch ( IOException i ) {
            i.printStackTrace();
        }
    }

    public void writeStudentsToFile(ObjectOutputStream out) throws IOException {

        for ( int i = 0; i < numberOfStudents; i++ ) {

            out.writeObject(studentListArray[i]);
        }

    }

//deletData() in the StudentList Class
public Student[] deleteData (String firstName)  
{     

    for(int i = 0; i<studentListArray.length; i++)  
    {  
        if(studentListArray[i].getFirstName().equals(firstName))  
        {  
        numberOfStudents++;  
        }  
    }         
    Student[] studentNewListArray = new Student[studentListArray.length-numberOfStudents];  

    for(int i = 0; i<studentNewListArray.length; i++)  
    {  

        if(studentListArray[i].getFirstName().equals(firstName)|| studentNewListArray[i].getFirstName().equals(null))  
        {         
            studentNewListArray[i] = studentListArray[i+1];  
            studentListArray[i+1] = null;  
        }  
        else  
        {  
            studentNewListArray[i] = studentListArray[i] ;   
        }  
    }  
    return studentNewListArray;  
}  

1 个答案:

答案 0 :(得分:0)

对于deletign做这样的事情......

public Student[] deleteData (String firstName)  {
    for(int counter=0;counter< studentListArray.length;counter++){
         if(studentListArray[counter].getFirstName().equals(firstName)){
               for(int counter1= counter;counter< studentListArray.length-1;counter1++){
                    studentListArray[counter1]=studentListArray[counter1 +1];
               }
               studentListArray[counter1+1]=null;
               break;
         }
    }
}