Java 尝试使用数组实现saveData()和deleteData()
SaveData和deleteData在我的studentList类中。我试图在我的UI中调用它们,但它们没有按预期工作 我也有学生课。有什么好主意吗Java 尝试使用数组实现saveData()和deleteData(),java,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
// 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;
}
对于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;
}
}
}
快速提问为什么不使用数组列表删除和保存将非常简单…讲师说请不要使用数组列表!粘贴你所有的代码可以告诉你什么是错误的…好的,我会这么做。问题之一是当你保存数据时,它会覆盖现有的数据。。。因此,当您加载程序时,您必须从文件中读取并填充数组,否则您将不断丢失数据。。。至于删除你的逻辑不正确将张贴一个sudo代码。。。再过一会儿……请告诉我怎么做;与int计数器不同;我假设在我的例子中计数器是int numberOfStudents;对吗?考虑一个例子,在数组中有10个元素,你想删除5个元素,所以计数器会把你带到5个元素,然后反循环将6个元素移动到5个元素的位置,最后一个将变为空…哼!衣冠楚楚的知道了!它起作用了。非常感谢你。。我想试试,如果我可以发布代码让你看看savaData的部分请!