Solved

Error when I add a Person to an array

Posted on 2008-10-22
13
359 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
13 Comments
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 22783125
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
ID: 22783162
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 60

Expert Comment

by:Kevin Cross
ID: 22783189
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 60

Expert Comment

by:Kevin Cross
ID: 22783200
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
ID: 22783213
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 60

Expert Comment

by:Kevin Cross
ID: 22783241
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
 

Author Comment

by:ccsk89
ID: 22783253
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
ID: 22783276
AH okay!!!! thanks.. but now I'm having problems with the removePerson method (ah this never ends!)
0
 
LVL 60

Accepted Solution

by:
Kevin Cross earned 500 total points
ID: 22783281
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
ID: 22783312
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
ID: 31509062
SUCH A LIFESAVER!!! THANK YOU!!!!
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 22783324
You too.
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 22783325
And you are most welcome.
0

Featured Post

The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

705 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