473,657 Members | 2,507 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Arraylike NullPointerExce ption

2 New Member
Hi,
I am currently taking Java II because I want to. Unfortunately, the teacher isn't the best and neither is the book. I'm getting a NullPointerExce ption when adding a contact to the arraylist ContactDatabase . I would just like to know what I'm overlooking so I can correct and continue with this lesson. I know the Contact is not being instantiated, but am at a lost for what I'm doing wrong. I appreciate any and all help. Thanks Annie.

Here's the code.

/**
* ContactDatabase .java
*
* This program implements a database of contacts that can be
* added to, searched, displayed, or items removed. An ArrayList
* is used to store the database.
*
* Created: Sun Apr 3 2005
* Updated: Sun July 30 2006 Amy Hickey
*
* @author Kenrick Mock
* @version 1
*
*/

import java.util.Scann er;
import java.util.Array List;

/**
* The Contact class stores the details for a single contact. There is no error
* checking on any of the input. Whatever string is passed in for a given
* attribute is accepted.
*/
class Contact
{
private String first, last, phone, email;

/**
* Constructors.
*/
public Contact()
{

}

public Contact(String first, String last, String phone, String email)
{
this.first = first;
this.last = last;
this.phone = phone;
this.email = email;
}

/*
* Accessor Methods
*/

public String getFirst()
{
return first;
}

public String getLast()
{
return last;
}

public String getPhone()
{
return phone;
}

public String getEmail()
{
return email;
}

/*
* Mutator Methods
*/
public void setFirst(String first)
{
this.first = first;
}

public void setLast(String last)
{
this.last = last;
}

public void setPhone(String phone)
{
this.phone = phone;
}

public void setEmail(String em)
{
this.email = em;
}



/*
* Return all fields concatenated into a string
*/
public String toString()
{
return last + ", " + first + ". " + phone + ", " + email;
}


public boolean equals(Object otherObject)
{
if (otherObject ==null)
{
return false;
}
else if (getClass() != otherObject.get Class())
{
return false;
}
else
{
Contact otherContact = (Contact)otherO bject;
return (first.equals(o therContact.fir st) &&
last.equals(oth erContact.last) &&
phone.equals(ot herContact.phon e)&&
email.equals(ot herContact.emai l));
}
}

}


/**
* The ContactDatabase class stores each contact in an arraylist.
* Methods exist to add new contacts, search contacts, delete, and print contacts
* to the console.
*/
public class ContactDatabase
{
private ArrayList<Conta ct> contacts; // ArrayList of contact
private static final int QUIT = 0; // Menu choices
private static final int ADD = 1;
private static final int LISTALL = 2;
private static final int SEARCH = 3;
private static final int DELETE = 4;

/**
* Default constructor - make a new ArrayList object with parameter type Contact
*/
public void createContactDa tabase()
{
contacts = new ArrayList<Conta ct>();

}

/**
* inputContact inputs contact information from the keyboard.
* It then stores this new contact in the contacts ArrayList.
*/
public void inputContact()
{
Contact myContact;

Scanner input = new Scanner(System. in);

System.out.prin tln("Enter the first name of a the person you wish to add, ie Karen");
String first = input.nextLine( );

System.out.prin tln("Enter the last name of a the person you wish to add, ie Brown");
String last = input.nextLine( );

System.out.prin tln("Enter your contact's phone number.");
String phone = input.nextLine( );

System.out.prin tln("Enter your contact's email address.");
String email = input.nextLine( );

myContact = new Contact(first, last, phone, email);
contacts.add(my Contact);


System.out.prin tln("The contacts details are:");
System.out.prin tln(contacts);
}


/**
* displayAll iterates through the ArrayList of contacts and outputs each one
* to the screen.
*/
public void displayAll()
{
System.out.prin tln("The contacts list contains:");
for (Contact entry : contacts)
System.out.prin tln (entry);
}

/**
* displayMatch inputs a keyword from the user.
* It then iterates through the ArrayList of contacts and outputs each one
* to the screen if the contact information contains the keyword.
*/
public void displayMatch()
{
int locationIndex = contacts.indexO f("first");
System.out.prin tln("Index location of the String \"Jeff\" is: " + locationIndex);

}

/**
* deleteMatch inputs a keyword from the user.
* It then iterates through the ArrayList of contacts and asks the user
* if the contact should be deleted, if the contact information contains the keyword.
*/
public void deleteMatch()
{

}

// Main class
public static void main(String[] args)
{
ContactDatabase cdb = new ContactDatabase ();
Scanner scan = new Scanner(System. in);
int choice = ADD;

// Main menu
while (choice != QUIT)
{
System.out.prin tln();
System.out.prin tln("Choose from the following:");
System.out.prin tln("0) Quit");
System.out.prin tln("1) Add new contact");
System.out.prin tln("2) List all contacts");
System.out.prin tln("3) Search contacts by keyword and display");
System.out.prin tln("4) Search contacts by keyword and remove");
choice = scan.nextInt();
switch (choice)
{
case ADD: cdb.inputContac t();
break;
case LISTALL: cdb.displayAll( );
break;
case SEARCH: cdb.displayMatc h();
break;
case DELETE: cdb.deleteMatch ();
break;
}
}
}
} // ContactDatabase
Mar 20 '07 #1
5 1444
RedSon
5,000 Recognized Expert Expert
Why do you have this method: createContactDa tabase()?
Mar 20 '07 #2
Ganon11
3,652 Recognized Expert Specialist
So that's it!

You have the method createContactDa tabase(), but from your documentation, this should be a constructor! Rename it as public ContactDatabase (), and when you create the object in main(), it will create its own Arraylist and get rid of the NullPointerExce ption.
Mar 20 '07 #3
r035198x
13,262 MVP
Hi,
I am currently taking Java II because I want to. Unfortunately, the teacher isn't the best and neither is the book. I'm getting a NullPointerExce ption when adding a contact to the arraylist ContactDatabase . I would just like to know what I'm overlooking so I can correct and continue with this lesson. I know the Contact is not being instantiated, but am at a lost for what I'm doing wrong. I appreciate any and all help. Thanks Annie.

Here's the code.

/**
* ContactDatabase .java
*
* This program implements a database of contacts that can be
* added to, searched, displayed, or items removed. An ArrayList
* is used to store the database.
*
* Created: Sun Apr 3 2005
* Updated: Sun July 30 2006 Amy Hickey
*
* @author Kenrick Mock
* @version 1
*
*/

import java.util.Scann er;
import java.util.Array List;

/**
* The Contact class stores the details for a single contact. There is no error
* checking on any of the input. Whatever string is passed in for a given
* attribute is accepted.
*/
class Contact
{
private String first, last, phone, email;

/**
* Constructors.
*/
public Contact()
{

}

public Contact(String first, String last, String phone, String email)
{
this.first = first;
this.last = last;
this.phone = phone;
this.email = email;
}

/*
* Accessor Methods
*/

public String getFirst()
{
return first;
}

public String getLast()
{
return last;
}

public String getPhone()
{
return phone;
}

public String getEmail()
{
return email;
}

/*
* Mutator Methods
*/
public void setFirst(String first)
{
this.first = first;
}

public void setLast(String last)
{
this.last = last;
}

public void setPhone(String phone)
{
this.phone = phone;
}

public void setEmail(String em)
{
this.email = em;
}



/*
* Return all fields concatenated into a string
*/
public String toString()
{
return last + ", " + first + ". " + phone + ", " + email;
}


public boolean equals(Object otherObject)
{
if (otherObject ==null)
{
return false;
}
else if (getClass() != otherObject.get Class())
{
return false;
}
else
{
Contact otherContact = (Contact)otherO bject;
return (first.equals(o therContact.fir st) &&
last.equals(oth erContact.last) &&
phone.equals(ot herContact.phon e)&&
email.equals(ot herContact.emai l));
}
}

}


/**
* The ContactDatabase class stores each contact in an arraylist.
* Methods exist to add new contacts, search contacts, delete, and print contacts
* to the console.
*/
public class ContactDatabase
{
private ArrayList<Conta ct> contacts; // ArrayList of contact
private static final int QUIT = 0; // Menu choices
private static final int ADD = 1;
private static final int LISTALL = 2;
private static final int SEARCH = 3;
private static final int DELETE = 4;

/**
* Default constructor - make a new ArrayList object with parameter type Contact
*/
public void createContactDa tabase()
{
contacts = new ArrayList<Conta ct>();

}

/**
* inputContact inputs contact information from the keyboard.
* It then stores this new contact in the contacts ArrayList.
*/
public void inputContact()
{
Contact myContact;

Scanner input = new Scanner(System. in);

System.out.prin tln("Enter the first name of a the person you wish to add, ie Karen");
String first = input.nextLine( );

System.out.prin tln("Enter the last name of a the person you wish to add, ie Brown");
String last = input.nextLine( );

System.out.prin tln("Enter your contact's phone number.");
String phone = input.nextLine( );

System.out.prin tln("Enter your contact's email address.");
String email = input.nextLine( );

myContact = new Contact(first, last, phone, email);
contacts.add(my Contact);


System.out.prin tln("The contacts details are:");
System.out.prin tln(contacts);
}


/**
* displayAll iterates through the ArrayList of contacts and outputs each one
* to the screen.
*/
public void displayAll()
{
System.out.prin tln("The contacts list contains:");
for (Contact entry : contacts)
System.out.prin tln (entry);
}

/**
* displayMatch inputs a keyword from the user.
* It then iterates through the ArrayList of contacts and outputs each one
* to the screen if the contact information contains the keyword.
*/
public void displayMatch()
{
int locationIndex = contacts.indexO f("first");
System.out.prin tln("Index location of the String \"Jeff\" is: " + locationIndex);

}

/**
* deleteMatch inputs a keyword from the user.
* It then iterates through the ArrayList of contacts and asks the user
* if the contact should be deleted, if the contact information contains the keyword.
*/
public void deleteMatch()
{

}

// Main class
public static void main(String[] args)
{
ContactDatabase cdb = new ContactDatabase ();
Scanner scan = new Scanner(System. in);
int choice = ADD;

// Main menu
while (choice != QUIT)
{
System.out.prin tln();
System.out.prin tln("Choose from the following:");
System.out.prin tln("0) Quit");
System.out.prin tln("1) Add new contact");
System.out.prin tln("2) List all contacts");
System.out.prin tln("3) Search contacts by keyword and display");
System.out.prin tln("4) Search contacts by keyword and remove");
choice = scan.nextInt();
switch (choice)
{
case ADD: cdb.inputContac t();
break;
case LISTALL: cdb.displayAll( );
break;
case SEARCH: cdb.displayMatc h();
break;
case DELETE: cdb.deleteMatch ();
break;
}
}
}
} // ContactDatabase
Please use code tags when posting code.
Also find time to read this.
Mar 21 '07 #4
annfarrell32
2 New Member
Please use code tags when posting code.
Also find time to read this.
Thanks, I never stopped to think about correcting the code that was provided. Just assumed it would be correct. You learn something new everyday.
Thanks again,
Annie
Mar 22 '07 #5
RedSon
5,000 Recognized Expert Expert
The code above is correct it just follows poor programming practices.
Mar 23 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

1
8570
by: K S Aldebaraan | last post by:
I'm trying to submit a form with an action of a servlet, and a view equal to the same jsp page. I'm not sure what I'm doing wrong, but keep getting a NullPointerException on the second line of code below: RequestDispatcher dispatcher = myConfig.getServletContext().getRequestDispatcher(view); dispatcher.forward(request, response); The funny thing is that it will do most of the database work it's supposed to, but then gives me the...
4
4068
by: gabryh | last post by:
Hi, The following code throws me NullPointerException. ..... public static boolean isEmpty(String value) { return ((value == null) || (value.trim().equals(""))); }
0
4409
by: Old-timer | last post by:
Not sure where else to post this. I'm sure I'm doing something wrong, but I wouldn't think a simple app would give me so much trouble. I've got a small test java class that I'm trying to have show up via tomcat. I'm running on Fedora Core 2, tomcat-4.1.27-13. I haven't noticed any difference if I start apache httpd-2.0.50-2.1 or not. Here are the errors: MsgAjp - -BAD packet signature 18245
13
1961
oll3i
by: oll3i | last post by:
private List<Klient> klienci; m_add_client.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try{
1
2443
by: ketand1 | last post by:
import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.sql.*; import java.lang.*; class DbAwt extends Frame implements ActionListener { private TextField t1, t2, t3;
2
2273
by: sokeefe | last post by:
I am trying to edit the GUI of a project in Netbeans. In particular, I am trying to add new JButtons. I get a NullPointerException when I try to add an Event to any given JButton (even ones that already exist) in my application using the Design Editor. I go about this by right-clicking on the JButton in the design editor, navigating to Events -> Action -> actionPerformed. The auto-generated code appears for a brief moment before it...
1
3187
by: sokeefe | last post by:
I am trying to edit the GUI of a project in Netbeans. In particular, I am trying to add new JButtons. I get a NullPointerException when I try to add an Event to any given JButton (even ones that already exist) in my application using the Design Editor. I go about this by right-clicking on the JButton in the design editor, navigating to Events -> Action -> actionPerformed. The auto-generated code appears for a brief moment before it...
1
17542
by: r035198x | last post by:
This exception occurs often enough in practice to warrant its own article. It is a very silly exception to get because it's one of the easiest exceptions to avoid in programming. Yet we've all got it before, lending proof to Einstein's statement: “Only two things are infinite, the universe and human stupidity ...”. Main Cause Dereferencing null. This is by far the more common cause of getting the exception. Reference types in both...
3
3328
by: chris123456789 | last post by:
Hi, when I run my code I get a NullPointerException:null. Here is the part of the code where the error occurs: import java.util.*; import java.io.*; public class Decrypt { ArrayList<String> dictionary; ArrayList<String> encryptedText;
0
8425
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8743
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8622
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7355
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6177
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2745
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.