【问题标题】:Java, removing an object from an ArrayList rewriting to text fileJava,从 ArrayList 中删除一个对象,重写为文本文件
【发布时间】:2015-10-19 04:11:45
【问题描述】:

我正在开发一个地址簿程序,但遇到了一些问题。我对 java 非常陌生,尤其是 ArrayLists/File I/O,出于某种原因,带有参数的方法让我很困惑。

所以这是我的问题...现在我正在努力允许用户删除联系人,但它似乎没有被删除。删除联系人后,我“查看”地址簿,所有联系人都在打印。我意识到在删除联系人后我必须重写文本文件,但这不起作用。我认为这与我如何写入文本文件以及如何添加联系人有关,但我对 ArrayLists/File IO 真的很陌生,由于某种原因,带有参数的方法让我非常困惑。感谢您的帮助,我正在寻找答案。

我把我所有的代码都放了,这样你就可以看到它是如何设置的,并在我认为问题可能来自的每个部分周围加上 ****。 (Contact 类是您的基本 getter 和 setter 以及构造函数。)

public class AddressBook implements Serializable{

private ArrayList<String> newBook = new ArrayList<String>();
private String dataFile;
private ArrayList<Contact> card =new ArrayList<Contact>(50);
private Contact[] contacts;
private int size = 0;
private int capacity = 0;
private String firstName;
private String lastName;
Scanner scan = new Scanner(System.in);
private Contact temp;

public static void main(String[] args) {
    AddressBook AB = new AddressBook();
    AB.addressBookMenu();       
}

//Method for address book menu
public void addressBookMenu() {
    String option = "";
    System.out.println("PLEASE SELECT ONE OF THE FOLLOWING OPTIONS: ");
    System.out.println("\t add   --> Add a new contact ");
    System.out.println("\t find  --> Find a contact ");
    System.out.println("\t edit  --> Edit an existing contact ");
    System.out.println("\t view  --> View the current address book");
    System.out.println("\t save  --> Save the current address book");
    System.out.println("\t quit  --> quit");
    System.out.println();
    option = scan.nextLine();

    while(!(option.equalsIgnoreCase("quit"))) {
        Contact con = new Contact(firstName, lastName);

        if(option.equalsIgnoreCase("add")) {
            System.out.println("Enter First Name: ");
            String tempFirst = scan.nextLine();
            System.out.println("Enter Last Name: ");
            String tempLast = scan.nextLine();

            con.setFirstName(tempFirst);
            con.setLastName(tempLast); 
            card.add(con);  
            writeContact();
        }   

******************************************************************************
        //View address book
        if(option.equalsIgnoreCase("view")) {
            System.out.println("ADDRESS BOOK: " + "\n" +
                    "==========================================");
            readContact();
            Collections.sort(card);
            printContacts();
        }

******************************************************************************          
        //Find and view a contact.
        if(option.equalsIgnoreCase("find")) {
            findContact(temp);  
        }

        //Edit contacts
        if(option.equalsIgnoreCase("edit")) {
            editContact();
        }   

        System.out.println();
        System.out.println("\n\nPLEASE SELECT ONE OF THE FOLLOWING OPTIONS: ");
        System.out.println("\t add   --> Add a new contact ");
        System.out.println("\t find  --> Find a contact ");
        System.out.println("\t edit  --> Edit an existing contact ");
        System.out.println("\t view  --> View the current address book");
        System.out.println("\t save  --> Save the current address book");
        System.out.println("\t quit  --> quit");
        System.out.println();
        option = scan.nextLine();
    }
}    

******************************************************************************  
public void writeContact() {
    try (FileOutputStream out = new FileOutputStream("addressbook.txt")) {  
        ObjectOutputStream os = new ObjectOutputStream(out);
        os.writeObject(card);
        os.close();     
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

******************************************************************************
public void readContact() {
    try (FileInputStream in = new FileInputStream("addressbook.txt")) {
        ObjectInputStream is = new ObjectInputStream(in);
        card = (ArrayList<Contact>)is.readObject();
        is.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
//Print out contacts 
public void printContacts() {
    for(Contact temp : card) {
        System.out.println(temp);
    }
}

public Contact findContact(Contact t) {
    System.out.println("Enter the LAST NAME of the contact you'd like to find: ");
    String tempLastName = scan.nextLine();
    for(Contact temp : card) {
        if(temp.getLastName().equalsIgnoreCase(tempLastName)) {
            System.out.println("\nCONTACT FOUND:");
            System.out.println(temp);
        }
        else if(temp.getLastName() == null || temp.getLastName().equalsIgnoreCase(tempLastName)) {
            System.out.println("Sorry but " + tempLastName + " is not located in this address book");
        }
    }
    return temp;
}

******************************************************************************  
public void editContact() {
    String editOption;
    System.out.print("HOW WOULD YOU LIKE TO EDIT A CONTACT: ");
    System.out.println("\tdelete  --> Delete a contact");
    System.out.println("\tchange  --> edit or replace a contact");
    editOption = scan.nextLine();

    if(editOption.equalsIgnoreCase("delete")) {
        findContact(temp);
        card.remove(temp);
        writeContact();
******************************************************************************  
    }   
}   
}

示例 添加 输入名字: 斯科特 输入姓氏: 史密斯

add 
Enter First Name: 
Bob
Enter Last Name: 
jones

edit
delete
Enter Last Name of Contact to delete:
jones

view 
ADDRESS BOOK: 
==========================================
FIRST NAME: Bob LAST NAME: Jones
FIRST NAME: Scott   LAST NAME: Smith

^^^^Still showing removed contact^^^^^

**EXPECTED OUTPUT**
view 
ADDRESS BOOK: 
==========================================
FIRST NAME: Scott   LAST NAME: Smith

【问题讨论】:

  • findContact(temp); 应该是 Contact contact = findContact(temp);,尽管我会质疑使用 temp 的必要性,因为 findContact 从不使用它
  • 是的,我对参数感到非常困惑,我知道这听起来很愚蠢,因为它是 101 个东西。我想我也会使用 findContact 来编辑联系人,所以我不必在 editContacts() 方法中放入相同的代码,但试图从 findContact() 中删除临时联系人我认为我必须返回值。 ...这项任务对我来说很困难,但我学到了很多东西。
  • 我会离开 findContact 来做这件事,寻找一个联系人;)

标签: java object file-io arraylist


【解决方案1】:

当您使用findContact 时,它会将return 匹配到您的Contact。在您现有的代码中,您忽略了返回结果。

相反,您应该使用类似...

public void editContact() {
    String editOption;
    System.out.print("HOW WOULD YOU LIKE TO EDIT A CONTACT: ");
    System.out.println("\tdelete  --> Delete a contact");
    System.out.println("\tchange  --> edit or replace a contact");
    editOption = scan.nextLine();

    if(editOption.equalsIgnoreCase("delete")) {
        Contact contact = findContact(temp);
        if (contact != null) {
            card.remove(contact);
            writeContact();
            readContact();
        }
    }   
}   

您的findContact 方法也不会返回它找到的内容,而是返回一些其他实例值,在我的测试中始终是null,它没有从List 中删除...

public Contact findContact() {
    Contact find = null;
    System.out.println("Enter the LAST NAME of the contact you'd like to find: ");
    String tempLastName = scan.nextLine();
    for (Contact temp : card) {
        if (temp.getLastName().equalsIgnoreCase(tempLastName)) {
            System.out.println("\nCONTACT FOUND:");
            System.out.println(temp);
            find = temp;
            break;
        }
    }
    if (find == null) {
        System.out.println("Sorry but " + tempLastName + " is not located in this address book");
    }
    return find;
}

nb:我把参数去掉是因为它只是混淆了问题

【讨论】:

  • 哦!!!好的,这是有道理的,老实说,我从您的评论中无法理解。谢谢疯狂,我真的很感激!你在我遇到的很多问题上帮助了我很多,不仅如此,你还经常解释有助于我学习的事情,我比你知道的更感激!只是觉得你们应该知道我们这些愚蠢的菜鸟可能不会表示感谢,但我们非常感激!
  • 最后一个问题,我写完Contacts()后还需要readContacts()吗?
  • 我们都是愚蠢的菜鸟,我们中的一些人只是让它看起来不错;)。很高兴它有帮助
  • 从技术上讲,不,你不需要在写完后重新读取列表,数据应该还是一样的
  • 好的,我想我明白了。再次感谢疯狂!我相信我很快就会再次和你说话!哈哈
猜你喜欢
  • 2017-10-24
  • 1970-01-01
  • 2014-05-04
  • 2015-08-05
  • 1970-01-01
  • 2017-08-02
  • 2016-02-14
  • 2021-08-14
  • 2010-11-21
相关资源
最近更新 更多