-2
    System.out.println("Welcome to the Personal Contact Assistant!");
    System.out.println("How can I help you?");
    System.out.println("(add) (get) (quit)");
    String option = input.nextLine();
    Contact[] Contacts;
    Contacts = new Contact[500];
    int index = 0;
    boolean finished = false;
    while(finished==false){
        switch (option) {
        case "add": 
            System.out.println("You have selected add.");
            Contact newContact = new Contact();//constructs new contact object called newContact                
            newContact.setNewInfo();//gathers input for newContact
            System.out.println("Contact Will be Saved as:");
            newContact.print();//prints gathered information
            Contacts[index] = newContact;//saves contact to array
            index++;//advances index
            System.out.println("Can I do something else for you? (add) (get) (quit)");
            option = input.nextLine();
            break;
        case "get":
            System.out.println("You have selected get.");
            System.out.println("Enter the contact's first name:");
            String tempName;
            tempName = input.nextLine();
            for(int i=0; i<499; i++){
                System.out.println(":"+i);
                if(Contacts[i].getFirstName().equals(tempName)){
                    System.out.println("Contact Found:");
                    Contacts[i].print();}
            }

            System.out.println("Can I do something else for you? (add) (get) (quit)");
            option = input.nextLine();
            break;

这些是我正在开发的联系人应用程序的添加和获取段。我的联系人类包含设置和获取联系人姓名、地址等的方法。我没有收到编译器错误,但是在运行程序时,我在 for 循环中收到了 nullpointerexception 错误。此外,输出只会从 System.out.println(":"+i); 打印 1 个数字。行(我添加它是为了找出实际发生了多少循环迭代),除非它找到具有该名字的联系人,在这种情况下,它会返回每个联系人的完整联系人信息,然后出错。我只希望它完成循环,打印与该名字的联系,然后返回主外循环。帮助?

4

1 回答 1

2

如果您在手动添加 500 个联系人之前运行 get(),则当 i 超过您添加的联系人数量时会抛出 ghis 行,因为无论您添加了多少联系人,我们都会转到 499。

       if(Contacts[i].getFirstName().equals(tempName)){

即使它找到了您正在寻找的那个,它也会一直运行到 499。有几种方法可以修复它。

  1. 如果期望你总能找到它,那么当你找到它时就停下来。

  2. 将循环更改为:

    对于 (i = 0; i < 索引; i++)

  3. 使用 ArrayList 或其他为您管理大小的集合类。那么你的搜索可以变成:

    对于(联系人联系人:联系人){

于 2013-09-16T02:34:52.667 回答