Solved

Error when I add a Person to an array

Posted on 2008-10-22
13
347 Views
Last Modified: 2013-11-23
Hi again,

   Another issue I've bumped into. I've written the code myself. This program uses two classes to create an address book. When I run the program and I type, "add" I get an error message that says,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
        at AddressBook.addPerson(AddressBook.java:38)
        at AddressBook.main(AddressBook.java:127)

I have no idea what I'm doing wrong. Is it the array that's screwing it up?

Thanks again in advance


EDIT:
    I think I fixed the addPerson Method I did this:
            public void addPerson(Person newPerson)
    {
   
        for(int indexPeople = 0; indexPeople<people.length-1; indexPeople++)
        {
            if(people[indexPeople] == null)
            {
                people[indexPeople] = newPerson;
            }
        }
    }

Does this seem right? It allows me to add a person when I compile it.

 But now when I type "print"  in the command prompt,  I get a new error message:
   
 Person@4a65e0
Person@4a65e0
Person@4a65e0
Person@4a65e0
Person@4a65e0
Person@4a65e0
Person@4a65e0
Person@4a65e0
Person@4a65e0
Person@4a65e0

I have no idea how this came to be printed, any ideas what I can do make it print the actual info?

Thanks again

     
/**HERE IS THE FIRST CLASS **/

 

public class Person

{

    private String firstName;

    private int yearBorn;

    private String phone;

 

    /**

     * <pre>

     * Description: 

     * Construct the strings and integer variables.

     * Pre:

     * None.

     * Post:

     * We have an object of class Person.

     * </pre>

     * 

     */   

    public Person()

    {

        firstName = "";

        yearBorn = 0;

        phone = "";

    }

 

    /**

     * <pre>

     * Description: 

     * Construct string and integer variables with specified firstName, yearBorn, and phone.

     * Pre:

     * None.

     * Post:

     * Have an objects of class Person that has specified values.

     * </pre>

     */

    public Person(String firstNameX, int yearBornX, String phoneX)

    {

        firstName = firstNameX;

        yearBorn = yearBornX;

        phone = phoneX;

    }

    

    /**

     * <pre>

     * Description: 

     * Set firstName.

     * Pre:

     * None.

     * Post:

     * Have format firstNameX with specified firstName.

     * </pre>

     */

    public void setFirstName(String firstNameX)

    {

        firstName = firstNameX;

    }

   

    /**

     * <pre>

     * Description: 

     * Return firstName.

     * Pre:

     * none

     * Post:

     * Return firstName.

     * </pre>

     */

    public String getFirstName()

    {

        return (firstName);

    }

 

    /**

     * <pre>

     * Description: 

     * Set yearBorn.

     * Pre:

     * None.

     * Post:

     * Have format yearBornX with specified yearBorn.

     * </pre>

     */

    public void setYearBorn(int yearBornX)

    {

        yearBorn = yearBornX;

    }

 

    /**

     * <pre>

     * Description: 

     * Return yearBorn.

     * Pre:

     * none

     * Post:

     * Return yearBorn.

     * </pre>

     */

    public int getYearBorn()

    {

        return (yearBorn);

    }

 

    /**

     * <pre>

     * Description: 

     * Set phone.

     * Pre:

     * None.

     * Post:

     * Have format phoneX with specified phone.

     * </pre>

     */

    public void setPhone(String phoneX)

    {

        phone = phoneX;

    }

 

    /**

     * <pre>

     * Description: 

     * Return phone.

     * Pre:

     * none

     * Post:

     * Return phone.

     * </pre>

     */

    public String getPhone()

    {

        return (phone);

    }

 

	/**

	 * <pre>

	 * Description: 

	 * prints the name, year born, and phone number.

	 * Pre:

	 * None.

	 * Post:

	 * Line with specified information will be printed.

	 * </pre>

	 *

	 */

    public void print()

    {

       System.out.println("name=" + firstName + "\t" + "yearBorn=" + yearBorn + "\t" + "phone=" + phone);

    }

}

 

 

 

/**HERE IS THE SECOND CLASS**/

 

 

import java.io.*;

import java.util.*; /** Scanner **/

import java.util.regex.*; /** Pattern **/

public class AddressBook

{

    Person[] people = new Person[10];

 

 

 

    /**

     * <pre>

     * Description: 

     * Add a new person to the people array.

     * Pre:

     * We have a class operand newPerson.

     * Post:

     * The people array will have a new person added to it.

     * </pre>

     * 

     */

    public void addPerson(Person newPerson)

    {

        for(int indexPeople = 0; indexPeople<people.length; indexPeople++)

        {

            if(people[indexPeople] == null)

            {

                people[indexPeople] = newPerson;

            }

        }

    }

 

    /**

     * <pre>

     * Description: 

     * Delete a person from the people array.

     * Pre:

     * None.

     * Post:

     * The people array will have a person deleted and have an open space in it.

     * </pre>

     *

     */

    public void removePerson(String firstName)

    {

        for(int indexPeople = 0; indexPeople<people.length; indexPeople++)

        {

            String[] newPeople = new String[people.length];

            if(newPeople[indexPeople] == firstName)

            {

                people[indexPeople] = people[indexPeople + 1];

            }

        }

    }

 

    /**

     * <pre>

     * Description: 

     * Print the format numerator and donominator.

     * Pre:

     * None.

     * Post:

     * Print.

 

 

     * </pre>

    *

	 */

    public void print()

    {

        for(int indexPeople = 0; indexPeople<people.length; indexPeople++)

        {

            System.out.println(people[indexPeople]);

        }

    }

    

   

    

    /**

	 * <pre>

	 * Description: 

	 * Test the program by performing few operations

	 * Pre:

	 * none

	 * Post:

	 * none

	 * </pre>

	 * 

	 */

    public static void main(String[] args)

    {

        AddressBook book = new AddressBook();

        

        Scanner scanner = new Scanner(System.in);

 

	String op1 = "";

        while(op1.equalsIgnoreCase(op1))

        {

            System.out.println("Do you want to do add or delete or print or quit");

	    op1 = new String(scanner.next());

            

            if(op1.equals("quit"))

            {

                return;

            }

            if(op1.equals("add"))

            {

                System.out.println("please type name, yearBorn, phone");

                String input1 = scanner.next();

                int input2 = scanner.nextInt();

                String input3 = scanner.next();

 

                book.addPerson(new Person(input1, input2, input3));

            }

            if(op1.equals("delete"))

            {

                System.out.println("please type name of person to be deleted");

	        String firstName = scanner.next();

                book.removePerson(firstName);

            }

            if(op1.equals("print"))

            {

                book.print();	

            }

 

        }

 

    }

}

Open in new window

0
Comment
Question by:ccsk89
  • 7
  • 6
13 Comments
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
This is doing what this code said to do:
for(int indexPeople = 0; indexPeople<people.length; indexPeople++)
        {
            System.out.println(people[indexPeople]);
        }

When you print an object, you get toString() representation of the object which by default is the Person@4a65e0 you are seeing.  If you intended this to be same as this:

public void print()
    {
       System.out.println("name=" + firstName + "\t" + "yearBorn=" + yearBorn + "\t" + "phone=" + phone);
    }

Then you have two options.  The first want without changing your Person code is to do this:

for(int indexPeople = 0; indexPeople<people.length; indexPeople++)
        {
            if (people[indexPeople] != null) { people[indexPeople].print(); }
        }

The alternative is to change the void print function in Person class to be an override of the toString() function.

public String toString()
    {
      return "name=" + firstName + "\t" + "yearBorn=" + yearBorn + "\t" + "phone=" + phone;
    }

The print code in your AddressBook class should now work as coded.

For the root of issue why you could not add to your array, is that you have to do what you did which is to check for null object in the array and create new Person on that index.  This is inefficient for what you are doing given you may want an address book with 11 people.

If your specifications allow it, try using a List<Person> object instead.

So:
List<Person> people = new ArrayList<Person>();

Then you can add people like this:
people.add(newPerson);
people.remove(index);

http://java.sun.com/j2se/1.4.2/docs/api/java/util/List.html

The remove will take a little bit of code adjustment, but to stay with what you are comfortable, you could search for the index of the Person object that matches the firstname and then use the people.remove with that index.

As you get more comfortable you may find easier ways to do this using the API.
0
 

Author Comment

by:ccsk89
Comment Utility
I'm not allowed to use List's. I'm supposed to use arrays only, so I tried the first option you said:

for(int indexPeople = 0; indexPeople<people.length; indexPeople++)
        {
            if (people[indexPeople] != null) { people[indexPeople].print(); }
        }
By doing that it compiled fine, but it when I add a person I get an error message:

Exception in thread "main" java.lang.NullPointerException
        at AddressBook.addPerson(AddressBook.java:40)
        at AddressBook.main(AddressBook.java:130)

Its not letting me add a person at all when I run the program. I have to keep the methods the way they are including the "void print" in class Person. Do you think it's because of the size of the array.. that's the only thing I can think of?

/**HERE'S THE FIRST CLASS**/
 

public class Person

{

    private String firstName;

    private int yearBorn;

    private String phone;

 

    /**

     * <pre>

     * Description: 

     * Construct the strings and integer variables.

     * Pre:

     * None.

     * Post:

     * We have an object of class Person.

     * </pre>

     * 

     */   

    public Person()

    {

        firstName = "";

        yearBorn = 0;

        phone = "";

    }
 

    /**

     * <pre>

     * Description: 

     * Construct string and integer variables with specified firstName, yearBorn, and phone.

     * Pre:

     * None.

     * Post:

     * Have an objects of class Person that has specified values.

     * </pre>

     */

    public Person(String firstNameX, int yearBornX, String phoneX)

    {

        firstName = firstNameX;

        yearBorn = yearBornX;

        phone = phoneX;

    }

    

    /**

     * <pre>

     * Description: 

     * Set firstName.

     * Pre:

     * None.

     * Post:

     * Have format firstNameX with specified firstName.

     * </pre>

     */

    public void setFirstName(String firstNameX)

    {

        firstName = firstNameX;

    }

   

    /**

     * <pre>

     * Description: 

     * Return firstName.

     * Pre:

     * none

     * Post:

     * Return firstName.

     * </pre>

     */

    public String getFirstName()

    {

        return (firstName);

    }
 

    /**

     * <pre>

     * Description: 

     * Set yearBorn.

     * Pre:

     * None.

     * Post:

     * Have format yearBornX with specified yearBorn.

     * </pre>

     */

    public void setYearBorn(int yearBornX)

    {

        yearBorn = yearBornX;

    }
 

    /**

     * <pre>

     * Description: 

     * Return yearBorn.

     * Pre:

     * none

     * Post:

     * Return yearBorn.

     * </pre>

     */

    public int getYearBorn()

    {

        return (yearBorn);

    }
 

    /**

     * <pre>

     * Description: 

     * Set phone.

     * Pre:

     * None.

     * Post:

     * Have format phoneX with specified phone.

     * </pre>

     */

    public void setPhone(String phoneX)

    {

        phone = phoneX;

    }
 

    /**

     * <pre>

     * Description: 

     * Return phone.

     * Pre:

     * none

     * Post:

     * Return phone.

     * </pre>

     */

    public String getPhone()

    {

        return (phone);

    }
 

	/**

	 * <pre>

	 * Description: 

	 * prints the name, year born, and phone number.

	 * Pre:

	 * None.

	 * Post:

	 * Line with specified information will be printed.

	 * </pre>

	 *

	 */

    public void print()

    {

       System.out.println("name=" + firstName + "\t" + "yearBorn=" + yearBorn + "\t" + "phone=" + phone);

    }

}
 
 
 

/**HERES THE SECOND CODE **/

import java.io.*;

import java.util.*; /** Scanner **/

import java.util.regex.*; /** Pattern **/

public class AddressBook

{

    Person[] people; // = new Person[10];
 
 
 

    /**

     * <pre>

     * Description: 

     * Add a new person to the people array.

     * Pre:

     * We have a class operand newPerson.

     * Post:

     * The people array will have a new person added to it.

     * </pre>

     * 

     */

    public void addPerson(Person newPerson)

    {

	    //newPerson = people[10];

	    

        for(int indexPeople = 0; indexPeople<people.length-1; indexPeople++)

        {

            if(people[indexPeople] == null) 

            {

                people[indexPeople] = newPerson;

            }

        }

    }
 

    /**

     * <pre>

     * Description: 

     * Delete a person from the people array.

     * Pre:

     * None.

     * Post:

     * The people array will have a person deleted and have an open space in it.

     * </pre>

     *

     */

    public void removePerson(String firstName)

    {

        for(int indexPeople = 0; indexPeople<people.length; indexPeople++)

        {

            String[] newPeople = new String[people.length];

            if(newPeople[indexPeople] == firstName)

            {

                people[indexPeople] = people[indexPeople + 1];

            }

        }

    }
 

    /**

     * <pre>

     * Description: 

     * Print the format numerator and donominator.

     * Pre:

     * None.

     * Post:

     * Print.

     * </pre>

    *

	 */

    public void print()

    {

        for(int indexPeople = 0; indexPeople<people.length; indexPeople++)

        {

            if(people[indexPeople] != null)

            {

                people[indexPeople].print();

            }

        }

    }

    

   

    

    /**

	 * <pre>

	 * Description: 

	 * Test the program by performing few operations

	 * Pre:

	 * none

	 * Post:

	 * none

	 * </pre>

	 * 

	 */

    public static void main(String[] args)

    {

        AddressBook book = new AddressBook();

        

        Scanner scanner = new Scanner(System.in);
 

	String op1 = "";

        while(op1.equalsIgnoreCase(op1))

        {

            System.out.println("Do you want to do add or delete or print or quit");

	    op1 = new String(scanner.next());

            

            if(op1.equals("quit"))

            {

                return;

            }

            if(op1.equals("add"))

            {

                System.out.println("please type name, yearBorn, phone");

                String input1 = scanner.next();

                int input2 = scanner.nextInt();

                String input3 = scanner.next();
 

                book.addPerson(new Person(input1, input2, input3));

            }

            if(op1.equals("delete"))

            {

                System.out.println("please type name of person to be deleted");

	        String firstName = scanner.next();

                book.removePerson(firstName);

            }

            if(op1.equals("print"))

            {

                book.print();	

        }

 

        }
 

    }

}

Open in new window

0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
A couple of things.

I just noticed that in the add person, you are doing this in loop -
 for(int indexPeople = 0; indexPeople<people.length-1; indexPeople++)

This will leave off the last index.  You need either < people.length OR <= people.length-1.

The size of the array only allows you to add 10 people maximum.  So if you are trying to add beyond that you cannot without having to add code that essentially creates a new array at a bigger size and copies the original objects form old array into the new one.  

With that said, currently on the first add you fill your entire 10 (well really 9 given first issue I pointed out ;)) spots with same new Person.

            if(people[indexPeople] == null)
            {
                people[indexPeople] = newPerson;
            }

What you will need to do is exit your loop once you have added to person to an index.

for(int indexPeople = 0; indexPeople<people.length-1; indexPeople++)
        {
            if(people[indexPeople] == null)
            {
                people[indexPeople] = newPerson;
                return; // this should work -- break; is another option
            }
        }

     
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
When you get a chance, re-examine this code as well...
You need to look for Person object that matches firstname supplied and then remove it from your address book, which in your implementation is making that index in array null.  This doesn't appear to do that, so try implementing a different way.

public void removePerson(String firstName)
    {
        for(int indexPeople = 0; indexPeople<people.length; indexPeople++)
        {
            String[] newPeople = new String[people.length];
            if(newPeople[indexPeople] == firstName)
            {
                people[indexPeople] = people[indexPeople + 1];
            }
        }
    }
0
 

Author Comment

by:ccsk89
Comment Utility
Ok ..I did that and I still keep getting the same error. If I'm trying to add a new person each time the user enters "add" and then the name, yearBorn, and phone, is this loop rewriting everything each time a new person is added?

Sorry I'm trying to think of other ways to fix this problem, but the error keeps messing me up!

is there another way to check if the array is empty rather than setting the

      people[indexPeople] == null

because thats the only thing I can think of that's messing it up.
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
When did you change this?
Person[] people; // = new Person[10];

I must have missed that.  Your people array is null which is why you are getting the null pointer exception.  You will have to leave as:

Person[] people = new Person[10];
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:ccsk89
Comment Utility
Would this be the correct way? What I think I'm doing is that if people[indexPeople].getFirstName() equals what the user inputs to delete then I set the people[indexPeople] to null and then shift every spot after that indexPeople up one.

   public void removePerson(String firstName)
    {
        for(int indexPeople = 0; indexPeople<people.length; indexPeople++)
        {

            if(people[indexPeople].getFirstName() == firstName)
            {
                people[indexPeople] = null;
                people[indexPeople+1] = people[indexPeople];
            }
        }
    }
0
 

Author Comment

by:ccsk89
Comment Utility
AH okay!!!! thanks.. but now I'm having problems with the removePerson method (ah this never ends!)
0
 
LVL 59

Accepted Solution

by:
Kevin Cross earned 500 total points
Comment Utility
For Strings you want to use .equals() and probably .equalsIgnoreCase() to be safe.

So people[indexPeople].getFirstName().equalsIgnoreCase(firstName).  You will also need to ensure that the given people[indexPeople] != null first.

This   people[indexPeople+1] = people[indexPeople];  doesn't do what you think it does.  You would have to do the reorganization part separately (in a different manner).  Given the way you are implementing this with a fixed address book checking everywhere for nulls, IMHO you don't need to worry about blank spots as you won't print null objects and the next time you add someone they will fill this spot.
0
 

Author Comment

by:ccsk89
Comment Utility
Okay PERFECT!!! this is what I did and it worked perfectly!

    public void removePerson(String firstName)
    {
        for(int indexPeople = 0; indexPeople<people.length; indexPeople++)
        {
            if(people[indexPeople] != null)
            {
                if(people[indexPeople].getFirstName().equalsIgnoreCase(firstName))
                {
                    people[indexPeople] = null;
                }
            }
        }
    }

I see why you said I need to use the .equals()etc.. (which is something I learned new today.. well a lot of stuff today)

You have been such a huge help, seriously! Thank you soo soo soo much! If I could give you 1000 points I would!

You have allowed me to get some sleep tonight! THANK YOU SO MUCH!!!!  

have a wonderful night!:)
0
 

Author Closing Comment

by:ccsk89
Comment Utility
SUCH A LIFESAVER!!! THANK YOU!!!!
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
You too.
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
And you are most welcome.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
sumDigits  challenge 7 60
network + 7 73
solarwind tftp server 2 30
Problem to start Neon 20 51
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now