这是我的代码片段。 数据是一个Object类型的二维数组。我之前已经将数据保存在JTable中。现在我已经写了 删除条目的代码。但是如果使用此代码,则只有第一个条目会从 JTable 中删除。
我无法理解这背后的原因。
请帮我解决这个问题。
-片段:
public void deleteActionPerformed(ActionEvent ae) {
String delname=tf4.getText();
int c=0;
try {
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("data.txt"));
data=(Object[][])ois.readObject();
for(;;c++) {
String x=(String)data[c][0];
if(x.equals(delname)) {
System.out.println("if working");
data[c][0]=null;
data[c][1]=null;
data[c][2]=null;
try {
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("data.txt"));
oos.writeObject(data);
} catch(Exception exc) {
System.out.println("error deleting data from"+" "+c+" row");
}
c++;
JOptionPane.showMessageDialog(new JFrame(),"contact deleted");
try {
ObjectInputStream oist=new ObjectInputStream(new FileInputStream("data.txt"));
data=(Object[][])oist.readObject();
JTable tb=new JTable(data,headers);
ObjectOutputStream oost=new ObjectOutputStream(new FileOutputStream("contacts.txt"));
oost.writeObject(tb);
} catch(Exception exc) {
System.out.println("error updating after deleting");
}
}
else
System.out.println("else working");
}
} catch(Exception exc) {
System.out.println("error reading data.txt for deleting");
}
}
最佳答案
正确缩进代码后,它会变得更加明显......
- 您正在循环中重新创建(并重新读取)文件,而不是在文件之后 - 为什么?
- 每次删除后都会写出一个新的 JTable 对象。
- 为什么要把它写出来?
- 您读得怎么样?
- 此外,循环内有两个
c++
,因此会跳过数组的第二个元素。 - 第三,如果出现异常,您只需继续(甚至不打印整个异常)。
关于java - 仅删除第一个联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5290688/