在Java中使用数组使用equals / not equals时出现问题

时间:2014-10-02 08:30:30

标签: java arrays

我正在使用数组为Java编写地址簿作业。我不知道如何在添加它们之前确保某人不在地址簿中,并确保它们在地址簿中以便删除它们。我有三个文件;希望我能正确地将代码复制到这里。关于我做错的任何想法都是最受欢迎的。

这是AddressBook类:

package addressbook;

public class AddressBook
{

    // declaring variable addressBook as reference
    // to an array of Person objects
    Person[] addressBook;

    // using a static field to keep track of 
    // the number of person objects
    public static int people = 0;

    // allocate memory for the array field in a constructor
    public AddressBook()
    {
        addressBook = new Person[2];
    }

    //Method to add a person object to the addressBook       
    public void AddPerson(Person person)
    {

        for (int i = 0; i < people; i++)
        {
            if (addressBook[i] != person)
            {
                // check to see if the number of person objects
                // is fewer than the number of spaces in the array
                if (people < addressBook.length)
                {
                    // add new person to array at the position
                    //  specified by variable people (starting with 0)
                    addressBook[people] = person;
                } // if there are too many person objects
                // to fit in the address book
                else
                {
                    // declare a temp array twice the length of address book
                    Person[] temp = new Person[addressBook.length * 2];
                    for (int j = 0; j < addressBook.length; j++) // put the references from the old address book into temp
                    {
                        temp[j] = addressBook[j];
                    }
                    //add the new person object into temp
                    temp[people] = person;
                    // copy the reference to temp into address book
                    addressBook = temp;
                }
                // increase person object count (since you just added a person)
                people++;
                // print to the console to see if method is working
                System.out.println("people = " + people + "\n"
                        + "addressBook.Length = " + addressBook.length);
            }
        }
    }
    // Method to search for a person by name.
    // Searches both first and last names
    // and puts the results into an array.

    public Person[] searchName(String name)
    {
        Person[] searchResults = new Person[addressBook.length];
        for (int i = 0; i < people; i++)
        {
            if ((addressBook[i].firstName.equals(name))
                    || (addressBook[i].lastName.equals(name)))
            {
                searchResults[i] = addressBook[i];
            }
        }
        return searchResults;
    }

    // Method to search for a person by ID number.
    // Puts the results into an array.
    public Person[] searchID(int id)
    {
        Person[] resultsList = new Person[addressBook.length];
        for (int i = 0; i < people; i++)
        {
            if (addressBook[i].idNumber == id)
            {
                resultsList[i] = addressBook[i];
            }
        }
        return resultsList;
    }

    //Method to remove a person object from the addressBook
    public void removePerson(int id)
    {
        for (int i = 0; i < people; i++) // Search by ID number.
        {
            if (addressBook[i].idNumber == id)
            {
                // copy the ref to the last person object in array
                // into the index location of the person object being removed
                addressBook[i] = addressBook[people - 1];
                // set the ref of the (formerly) last person object to null
                addressBook[people - 1] = null;
                // decrease person object count (since you just removed a person) 
                people--;
            }
        }
        // If your count of people is 25% or less than the 
        // length of your address book
        if (people <= (addressBook.length / 4))
        {
            // declare a temp array half the length of address book
            Person[] temp = new Person[addressBook.length / 2];
            for (int j = 0; j < people; j++) // put the references from the old address book into temp
            {
                temp[j] = addressBook[j];
            }
            // copy the reference to temp into address book
            addressBook = temp;
        }
        // print to the console to see if method is working
        System.out.println("Count= " + people + "\n"
                + "addressBook.Length= " + addressBook.length);
    }

    // Prints the array to the console
    public void PrintAddressBook()
    {
        for (int i = 0; i < addressBook.length; i++)
        {
            System.out.println(addressBook[i]);
        }
    }
}

这是Person类:

package addressbook;

public class Person
{
    public String firstName, lastName;
    public int idNumber = 0;
    public static int nextIdNumber;

    public Person(String fn, String ln)
    {
        firstName = fn;
        lastName = ln;
        nextIdNumber++;
        idNumber = nextIdNumber;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public void setFirstName(String newFirstName)
    {
        firstName = newFirstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public void setLastName(String newLastName)
    {
        lastName = newLastName;
    }


    @Override
    public String toString()
    {
        return ("First name: " + firstName + "\n"
                + "Last name: " + lastName + "\n"
                + "Full name: " + firstName + " " + lastName + "\n"
                + "ID number: " + idNumber);
    }

    public void printInformation()
    {
        System.out.println(lastName + ", " + firstName + ", " + idNumber);
    }
}

这是AddressBookTester:

package addressbook;

public class AddressBookTester {

    public static void main(String[] args) {

        AddressBook addressBook = new AddressBook();

        System.out.println("-----Testing a Person Constructor-----");
        System.out.println("--------using ToString Method--------\n");
        Person person1 = new Person("Helen", "Mirren");
        System.out.println(person1);
        System.out.println();

        Person person2 = new Person("Helen", "Thomas");
        System.out.println(person2);
        Person person3 = new Person("Thomas", "Wolfe");
        System.out.println(person3);
        Person person4 = new Person("Robert", "Redford");
        System.out.println(person4);
        Person person5 = new Person("Robbie", "Robertson");
        System.out.println(person5);

        System.out.println("--Testing Add Person Method--");
        addressBook.AddPerson(person1);
        addressBook.AddPerson(person2);
        addressBook.AddPerson(person3);
        addressBook.AddPerson(person4);
        addressBook.AddPerson(person5);
        addressBook.PrintAddressBook();

        System.out.println("----Testing Search by Name Method------");
        //create return Person object array for searchName function
        Person[] searchList = addressBook.searchName("Helen");
        for (int i = 0; i < searchList.length; i++) {
            System.out.println(searchList[i]);
        }

        System.out.println("----Testing Search by ID Method------");
        Person[] results = addressBook.searchID(5);
        for (int i = 0; i < results.length; i++) {
            System.out.println(results[i]);
        }

        System.out.println("----Testing Remove Person Method------");
        addressBook.removePerson(4);
        addressBook.removePerson(3);
        addressBook.removePerson(2);
        addressBook.PrintAddressBook();
    }
}

当我运行它时,我得到:

/*run:
-----Testing a Person Constructor-----
--------using ToString Method--------

First name: Helen
Last name: Mirren
Full name: Helen Mirren
ID number: 1

First name: Helen
Last name: Thomas
Full name: Helen Thomas
ID number: 2
First name: Thomas
Last name: Wolfe
Full name: Thomas Wolfe
ID number: 3
First name: Robert
Last name: Redford
Full name: Robert Redford
ID number: 4
First name: Robbie
Last name: Robertson
Full name: Robbie Robertson
ID number: 5
--Testing Add Person Method--
null
null
----Testing Search by Name Method------
null
null
----Testing Search by ID Method------
null
null
----Testing Remove Person Method------
Count= 0
addressBook.Length= 1
Count= 0
addressBook.Length= 0
Count= 0
addressBook.Length= 0
BUILD SUCCESSFUL (total time: 0 seconds)
*/

感谢有关如何修复此代码的任何想法。我很擅长编码,显然......

2 个答案:

答案 0 :(得分:0)

我现在无法彻底阅读您的代码,但我会尝试对我观察到的一些问题提供一些提示。

没有。 1:

searchX()方法中,您返回的数组Person与地址簿的大小完全相同。在循环地址簿的方法中(提示使用foreach而不是索引循环),然后调用searchResults[i] = addressBook[i];。这可能会导致结果数组中的大量空条目。

您可能希望为searchResults添加不同的索引,并仅在添加条目时增加该索引。这样所有的空条目都在数组的末尾,您可以轻松地复制该数组,并在最后省略空白部分。

没有。 2:

一般情况下,如果您允许使用ListSet等集合,请使用这些集合而不是数组。

没有。 3:

不要将对象与{= 1}中的==或!=进行比较,因为您可以使用相同的数据创建两个对象,并且您不会看到它们因为==比较对象的缩进而不是相等。

没有。 4:

在致电if( addressBook[i] != person)时,您未获得打印状态,这表明存在错误。

尝试并调​​试您的代码,您应该看到addPerson()将导致无迭代,因为for (int i = 0; i < people; i++)最初为0,因此永远不会满足people。因此,没有任何东西被添加到你的数组中。

我认为这是真正的问题:

您的i < 0方法结构错误。除了上面提到的addPerson问题之外,您还要多次添加每个新人,因为您不会终止循环,但只要i < 0每个条目都适用,就会添加该人。在新人的情况下阵列。

尝试将其更改为以下伪代码:

addressBook[i] != person

没有。 5:

作为旁注,请尝试坚持Java代码约定,例如方法名称始终以小写字母开头,即boolean personInArray = searchById( person.getId() ); if( !personInArray ) { if( people == addressBook.length) { //resize the array, since it is full and the person should be added } //add the person addressBook[people] = person; people++; } 而不是addPerson。虽然这更像是一种风格问题,但它可以帮助您和其他人调试和理解您的代码。

答案 1 :(得分:0)

首先是一个非常明确的问题:

首先将person计数管理员初始化为0,然后在AddPerson()方法中启动循环执行:

for(int i=0;i<person;i++){
...
}

person = 0起,它甚至不会进入循环,因为0不小于0.

其次,您正在对对象执行==比较,这肯定会出错。原因如下:

==!=是参考比较,即==仅在被比较的两个对象引用内存中的同一对象时才返回true。

相反,您应该使用.equals(...)函数,但由于您的Person类没有扩展任何内容,因此默认使用Object.equals()超类方法,这与上面的方法相同。

因此,进行比较的正确方法是覆盖equals()类的Person方法,使其返回true,例如名字和姓氏相同,或者以您的标准为准。同时,您还应确保覆盖hashCode()方法以遵守这两种方法之间的约定。您可以阅读更多相关信息,例如这里: http://javarevisited.blogspot.dk/2011/02/how-to-write-equals-method-in-java.html