Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中使用数组时遇到equals/notequals问题_Java_Arrays - Fatal编程技术网

在Java中使用数组时遇到equals/notequals问题

在Java中使用数组时遇到equals/notequals问题,java,arrays,Java,Arrays,我正在为Java编写一个地址簿作业,使用数组。我被困在如何确保某人在添加之前不在通讯簿中,并确保他们在通讯簿中以便删除他们。我有三个档案;希望我能将代码正确地复制到这里。任何关于我做错了什么的想法都是非常感谢的 这是AddressBook类: package addressbook; public class AddressBook { // declaring variable addressBook as reference // to an array of Perso

我正在为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]);
        }
    }
}
这是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();
    }
}

感谢您提供有关如何修复此代码的任何想法。我对编码非常陌生,显然…

我现在无法彻底阅读您的代码,但我将尝试就我观察到的一些要点给出一些提示

第一:

在searchX方法中,返回一个与通讯簿大小完全相同的Person数组。在您在addressbook提示上循环的方法中,使用foreach而不是按索引循环,然后调用searchResults[i]=addressbook[i];。这可能会导致结果数组中出现大量空项

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

第2号:

通常,如果允许使用列表、集合等集合,请使用这些集合而不是数组

第3号:

不要将对象与==或!=进行比较就像在if地址簿[i]!=person,因为您可以使用相同的数据创建两个对象,但由于==比较对象的一致性而不是相等性,您看不到它们是相等的

第4号:

当你打电话给addPerson时,你没有收到打印的状态,这应该表明出了问题

尝试并调试您的代码,对于int i=0,您应该会看到这一点;我喜欢人;i++不会导致迭代,因为人最初是0,因此i<0永远不会满足。因此,不会向数组中添加任何内容

我认为真正的问题是:

addPerson方法的结构错误。除了上面提到的i<0问题外,您还要多次添加每个新的联系人,因为您不终止循环,而是在addressBook[i]!=如果是新人,则数组中的每个条目都为true

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

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++;
}
第5号:


作为旁注,请尽量遵守Java代码惯例,例如,方法名称总是以小写字符开头,即addPerson而不是addPerson。虽然这更多的是风格问题,但它将帮助您和其他人调试和理解您的代码。

首先有一个非常明显的问题:

首先将person count keeper初始化为0,然后在AddPerson方法中启动循环以执行:

for(int i=0;i<person;i++){
...
}
由于person=0,它甚至不会进入循环,因为0不小于0

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

==和!=是引用比较,即,仅当正在比较的两个对象引用内存中的同一对象时,==才会返回true

相反,您应该使用.equals。。。函数,但由于Person类不扩展任何内容,因此这将默认为Object.equals超类方法,该方法与上述方法等效

因此,进行比较的正确方法是重写Person类的equals方法,这样,如果名字和姓氏相同,或者无论您的条件是什么,它都会返回true。同时,您还应该确保重写hashCode方法,以遵守这两个方法之间的约定。您可以阅读更多关于此的信息,例如:

尝试查找如何在Java中比较对象。特别是使用equals/hashcodec,你就不能用一个Set,喝杯咖啡吗?@Mena我想他不允许用Set。这是一个家庭作业。@Lorien Kurt说的是,你不能用Java做这件事:if addressBook[i]!=人员,检查如何比较两个对象@KurtDuBois,谢谢你的建议。是因为addressBook[i]包含内存地址,而不是实际变量吗?我们还没有学习hashcode。谢谢@Thomas!这些都是很好的观点。令人沮丧的是,就在上周,我用C语言成功地完成了同样的任务,所以我真的没想到我会有这么大的改变。不幸的是,我不允许使用列表或集合。我会采纳你的建议,看看是否能改进我的代码。谢谢你编辑的建议@Thomas;明天我得仔细看一看这里很晚了。还感谢您对Java代码约定的说明。老实说,我从我的C代码开始编辑它,所以我错过了一些IDE没有抓住的案例约定;既然我只能选一个,我就和托玛一起去
s、 因为他是第一个,而且至少我理解了他的答案中与Java代码命名约定有关的部分。我还在研究“平等”这个难题。我以为是一个同学解决了这个问题,但当我测试他的代码时,很多代码都不起作用,所以至少我不是一个人。。。我期待着有一天,学习列表和设置@Lorien看一看4号,我认为这是你问题的核心。除此之外,你一定要仔细研究一下列表和集合,它们并不难理解:列表提供了一种排序,在需要时可以增长,集合也可以增长,但并不总是提供一种排序,除非你使用特殊的集合,如TreeSet或LinkedHashSet,但最有用的是集合不允许重复。为了使事情变得正确,您需要正确地实现equals和hashCode,所以也来看看它们。Thomas,再次感谢您!这些都非常有用。我们很快就要完成另一项任务了,我们要使用列表,所以至少我会很快试用这些列表。你是对的,布尔值确实有用。我的教授帮我完成了最后一部分;我有布尔背景词。这最终起作用了:布尔值isInBook=false;对于int i=0;我喜欢人;i++{if addressBook[i]==person{isInBook=true;}}}if!“谢谢你,”塞巴斯蒂安·阿克塞尔森!你是对的,那个for循环根本不应该在那里。我想这是因为我在晚上做了太多太晚的编辑,当时我正在尝试各种各样的东西。谢谢你抓住了!至于equals方法的问题,你的回答确实让我对这个问题有了更多的看法,但是我们还没有研究任何关于hashCode的内容,所以我可能不得不用另一种方法来解决equals方法的问题。但我非常感谢你在这方面花时间。我希望我有足够的代表来投票;一旦我这样做了,我将投票表决这个答案!不用担心,很高兴我能帮忙!您的问题非常常见,java肯定知道。对于赋值,重写hashCode方法可能不是必需的,但是为了将来的参考,这样做被认为是良好的做法,因为equals和hashCode方法应该相互遵循。
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++;
}
for(int i=0;i<person;i++){
...
}