Address book .... importing text file

I am designing an address book which opens a text file called AddressBook.txt which reads in the information in the following format:

lastname,firstname,street,city,state,zip,phonenumber,birthday,persontype

lastname2,firstname2,street2,city2,state2,zip2,phonenumber2,birthday2,persontype2

etc. (with a maximum entries of 500)

I am having a problem reading in the information without the commas and wrapping to the next line. I can either use the BufferedReader or Scanner to input the file and as you can see below, my code is not complete yet. I can't figure out how to code the storeAddress()

method in order to get the addressBookEntries[] to include the necessary information for outputting, sorting, etc. If I can get the information read into the addressBookEntries[], I think I will probably be able to proceed in the rest of the required tasks (i.e. sorting by last name, searching by last name, etc.)

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

import java.util.*;

import java.text.SimpleDateFormat;

import java.io.*;

import java.lang.*;

/**

*

* @created September 14, 2004

*

*

* This program uses a JFrame to manipulate data and form an

* address book. The user will be able to load data from a file,

* sort it by last name, print the address, phone number, and date

* of birth, print the names of people whos birthday are between 2

* dates, print the names of people between 2 last names, and/or

* print the names of different person types.

*/

publicclass AddressBookextends JPanelimplements ActionListener{

JFrame frame;

finalint numButtons = 7;

JRadioButton[] radioButtons =new JRadioButton[numButtons];

JButton process =new JButton("Process Request");

JLabel title;

JTextArea output =new JTextArea(30,50);

int MAX_ADDRESS_ENTRIES = 500;

AddressBookEntry addressBookEntries[] =

new AddressBookEntry[MAX_ADDRESS_ENTRIES];

String FILE_NAME="AddressBook.txt";

public AddressBook(JFrame frame){

super(new BorderLayout());

this.frame=frame;

JPanel choicePanel = createSimpleDialogBox();

choicePanel.setBorder(BorderFactory.createTitledBorder("Choices" +

" to choose from:"));

title =new JLabel("<html><h2> Thank you for opening the " +

"Address Book. " +

"Please Press the \"Process Request\" " +

"after making a choice.</h2></html>\n",JLabel.CENTER);

title.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));

output.setEditable(false);

add(title, BorderLayout.NORTH);

add(choicePanel, BorderLayout.CENTER);

add(output, BorderLayout.SOUTH);

}

final ButtonGroup group =new ButtonGroup();

final String saveCommand ="Save";

final String sortByLN ="Sort by Last Name";

final String searchLNCommand ="Search By Last Name";

final String printAPD ="Print address, phone number, and DOB";

final String printNamesDOB ="Print names of people whose birthday" +

" falls between 2 dates";

final String printNamesLN ="Print names of people who fall" +

" between 2 last names";

final String printPType ="Print all family members, friends, or" +

" business associates";

private JPanel createSimpleDialogBox(){

radioButtons[0] =new JRadioButton(

"<html>Save the address file</html>");

radioButtons[0].setActionCommand(saveCommand);

radioButtons[1] =new JRadioButton(

"<html>Sort the address file by last name</html>");

radioButtons[1].setActionCommand(sortByLN);

radioButtons[2] =new JRadioButton(

"<html>Search the address file by last name</html>");

radioButtons[2].setActionCommand(searchLNCommand);

radioButtons[3] =new JRadioButton(

"<html>Print the address, phone number, and DOB of a specified" +

" person</html>");

radioButtons[3].setActionCommand(printAPD);

radioButtons[4] =new JRadioButton(

"<html>Print the names of people whose birthday falls between" +

" two dates</html>");

radioButtons[4].setActionCommand(printNamesDOB);

radioButtons[5] =new JRadioButton(

"<html>Print the names of people who fall between two" +

" specified last names</html>");

radioButtons[5].setActionCommand(printNamesLN);

radioButtons[6] =new JRadioButton(

"<html>Print all family members, friends, <u>OR</u>" +

" business associates</html>");

radioButtons[6].setActionCommand(printPType);

for (int i=0; i<numButtons; i++){

group.add(radioButtons[i]);

}

//set the first button (open file) to be selected

radioButtons[0].setSelected(true);

return createPane(radioButtons, process);

}

private JPanel createPane(JRadioButton[] radioButtons,

JButton showButton){

int numChoices = radioButtons.length;

JPanel box =new JPanel();

box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));

for (int i = 0; i >< numChoices; i++){

box.add(radioButtons[i]);

}

JPanel pane =new JPanel(new BorderLayout());

pane.add(box, BorderLayout.NORTH);

pane.add(showButton, BorderLayout.SOUTH);

return pane;

}

publicvoid actionPerformed(ActionEvent e){

String command = group.getSelection().getActionCommand();

//else if button pushed is save

if (command == saveCommand){

// save file

}

//else if button pushed is search by last name

elseif (command == sortByLN){

// search by last name

}

//else if button pushed is sort by last name

elseif (command == searchLNCommand){

// sort by last name

//print to screen

}

//else if button pushed is display address, ph#, dob

elseif (command == printAPD){

// display "search by last name" dialog

//search last names

// if last name found

// print data

// else

// print error notification "person not found"

}

//else if button pushed is list names of people whose

//bday between 2 days

elseif (command == printNamesDOB){

// ask for which dates

//search bday

// print to screen

}

//else if button pushed is print names of people between 2 last names

elseif (command == printNamesDOB){

// ask for which two last names

//search last names

// if people found

// print to screen

//else

//print error notification "no one found"

}

//else if button pushed is print all family members, friends

//or business associates

elseif (command == printPType){

//ask for what person type

//search person types

//if people found

//print to screen

//else print "no one found"

}

}

publicvoid storeAddress(File addressFile){

Scanner sc=null;

String lname,fname,street,city,state,zip,phone,persontype,bday;

try{

// Delimiters specifiy where to parse tokens in a scanner

sc =new Scanner(addressFile).useDelimiter("\\s*[\\p{,}*\\s+]\\s*");

}

catch (FileNotFoundException fnfe){

JOptionPane.showMessageDialog(this,"Could not open the file");

System.exit(-1);

}

for(int i=0; i<MAX_ADDRESS_ENTRIES; i++){

while (sc.hasNext()){

lname=(sc.next());

if (!lname.equals("")){

addressBookEntries[i].setLName()=lname;

}

}

}

}

publicclass AddressBookEntry{

private extPerson address;

private String date;

private extPerson ExtPerson;

}

publicclass Person{

protected String lastName, firstName;

private String address;

private String city;

private String state;

private String zipcode;

private String homephone;

private String extPersonType;

private Date bday;

SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy-mm-DD");

public String toString(){

return lastName+" "+firstName;

}

publicvoid setLName(String last){

lastName=last;

}

publicvoid setFName(String first){

firstName=first;

}

public String getLastName(){

return lastName;

}

public String getFirstName(){

return lastName;

}

public Person(){

lastName="";

firstName="";

}

public Person(String first, String last){

setLName(last);

setFName(first);

}

//Set the address and return it

publicvoid setAddress( String addr ){

address = addr;

}

public String getAddress(){

return address;

}

//set the city and return it

publicvoid setCity( String town ){

city = town;

}

public String getCity(){

return city;

}

//set the state and return it

publicvoid setState( String st )

{

state = st;

}

public String getState()

{

return state;

}

//Set the zip code and return it

publicvoid setZipCode( String zip ){

zipcode = zip;

}

public String getZipCode(){

return zipcode;

}

//Set the home phone and return it

publicvoid setHomePhone( String homeph ){

homephone = homeph;

}

public String getHomePhone(){

return homephone;

}

//Set the bday and return it

public Date getBday(){

return bday;

}

publicvoid setBday(Date newBday){

bday = newBday;

dateFormat.format(bday);

}

//Set the extPerson type and return it

public String getPType(){

return extPersonType;

}

publicvoid setPBusiness(){

extPersonType ="Business Associate";

}

publicvoid setPFamily(){

extPersonType ="Family Member";

}

publicvoid setPFriend(){

extPersonType ="Friend";

}

}

publicclass extPersonextends Person{

}

//new clss People

publicclass People{

int MAX_PEOPLE=500;

BufferedReader bf;

public String toString(){

StringBuffer sb=new StringBuffer();

for (int i=0; i><nPeople; i++)

sb=sb.append(group[i]+"\n");

return sb.toString();

}

publicvoid read(){

String str;

try{

bf=new BufferedReader(new FileReader(new File(FILE_NAME)));

str=bf.readLine();

while (str!=null){

insert(str);

str=bf.readLine();

}

}

catch (IOException e){

// Will jump to here on an eof condition.

}

try{

bf.close();

}

catch (IOException e){}

}

publicvoid save(){

try{

PrintWriter pw=new PrintWriter(FILE_NAME);

for (int i=0; i><nPeople; i++)

pw.println(group[i]+",");

pw.close();

}

catch (FileNotFoundException fne){

System.out.println("Could not Save "+FILE_NAME);

}

}

public People(){

group=new extPerson[MAX_PEOPLE];

nPeople=0;

}

publicboolean insert(String data){

if (nPeople><MAX_PEOPLE){

//extPerson guy=new extPerson(data);

//group[nPeople]=guy;

nPeople++;

returntrue;

}

else{

JOptionPane.showMessageDialog(null,"Error in People" +

"::insert: Max size reached.");

returnfalse;

}

}

publicvoid clear(){

// This loop frees up the memory used by each extPerson

for (int i=0; i><nPeople; i++)

group[i]=null;

nPeople=0;

}

extPerson group[];

int nPeople;

}

/**

* Create the GUI and show it. For thread safety,

* this method should be invoked from the

* event-dispatching thread.

*/

publicstaticvoid createAndShowGUI(){

JFrame.setDefaultLookAndFeelDecorated(true);

JDialog.setDefaultLookAndFeelDecorated(true);

JFrame frame =new JFrame("Address Book Program");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container c = frame.getContentPane();

c.add(new AddressBook(frame));

frame.pack();

frame.setVisible(true);

}

publicstaticvoid main (String s[]){

//Schedule a job for the event-dispatching thread:

//creating and showign this application's GUI

javax.swing.SwingUtilities.invokeLater(new Runnable(){

publicvoid run(){

createAndShowGUI();

}

});

}

}

>

[25470 byte] By [nichole120] at [2007-9-30 17:57:03]
# 1

I would very strongly advise you to separate the main functionality from the UI.

"storeAddress" is a poor method name. It suggests that you're trying to store the addresses, rather than loading them, which apparently is what you're really trying to do.

Since the data you're reading is line-oriented, I'd suggest using line-oriented parsing, such as BufferedReader.readLine, or one of the line-oriented Scanner methods. (like "findInLine"? Scanner is new in 1.5 and I'm not very familiar with it.)

paulcw at 2007-7-6 14:34:13 > top of Java-index,Java Essentials,Java Programming...
# 2

Ok, I have changed my code to reflect your suggested changes, but I'm still unsure how to use the findInLine you suggested.... This is all very new to me and I've been looking on the java website for suggestions, but I'm still stumped on how to pull this together. I'm unsure on how to set the lastname,firstname,etc. for retrieval...

Here's my code:

//ADDRESS BOOK

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

import java.util.*;

import java.text.SimpleDateFormat;

import java.io.*;

import java.lang.*;

/**

*

* @created September 14, 2004

*

*

* This program uses a JFrame to manipulate data and form an

* address book. The user will be able to load data from a file,

* sort it by last name, print the address, phone number, and date

* of birth, print the names of people whos birthday are between 2

* dates, print the names of people between 2 last names, and/or

* print the names of different person types.

*/

public class AddressBook extends JPanel implements ActionListener{

JFrame frame;

final int numButtons = 7;

JRadioButton[] radioButtons = new JRadioButton[numButtons];

JButton process = new JButton("Process Request");

JLabel title;

JTextArea output = new JTextArea(30,50);

int MAX_ADDRESS_ENTRIES = 500;

AddressBookEntry addressBookEntries[] = new

AddressBookEntry[MAX_ADDRESS_ENTRIES];

public AddressBook(JFrame frame){

super(new BorderLayout());

this.frame=frame;

JPanel choicePanel = createSimpleDialogBox();

choicePanel.setBorder(BorderFactory.createTitledBorder("Choices" +

" to choose from:"));

title = new JLabel("<html><h2> Thank you for opening the " +

"Address Book. " +

"Please Press the \"Process Request\" " +

"after making a choice.</h2></html>\n",JLabel.CENTER);

title.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));

output.setEditable(false);

add(title, BorderLayout.NORTH);

add(choicePanel, BorderLayout.CENTER);

add(output, BorderLayout.SOUTH);

}

final ButtonGroup group = new ButtonGroup();

final String saveCommand = "Save";

final String sortByLN = "Sort by Last Name";

final String searchLNCommand = "Search By Last Name";

final String printAPD = "Print address, phone number, and DOB";

final String printNamesDOB = "Print names of people whose birthday" +

" falls between 2 dates";

final String printNamesLN = "Print names of people who fall" +

" between 2 last names";

final String printPType = "Print all family members, friends, or" +

" business associates";

private JPanel createSimpleDialogBox(){

radioButtons[0] = new JRadioButton(

"<html>Save the address file</html>");

radioButtons[0].setActionCommand(saveCommand);

radioButtons[1] = new JRadioButton(

"<html>Sort the address file by last name</html>");

radioButtons[1].setActionCommand(sortByLN);

radioButtons[2] = new JRadioButton(

"<html>Search the address file by last name</html>");

radioButtons[2].setActionCommand(searchLNCommand);

radioButtons[3] = new JRadioButton(

"<html>Print the address, phone number, and DOB of a specified" +

" person</html>");

radioButtons[3].setActionCommand(printAPD);

radioButtons[4] = new JRadioButton(

"<html>Print the names of people whose birthday falls between" +

" two dates</html>");

radioButtons[4].setActionCommand(printNamesDOB);

radioButtons[5] = new JRadioButton(

"<html>Print the names of people who fall between two" +

" specified last names</html>");

radioButtons[5].setActionCommand(printNamesLN);

radioButtons[6] = new JRadioButton(

"<html>Print all family members, friends, <u>OR</u>" +

" business associates</html>");

radioButtons[6].setActionCommand(printPType);

for (int i=0; i<numButtons; i++){

group.add(radioButtons[i]);

}

//set the first button (open file) to be selected

radioButtons[0].setSelected(true);

return createPane(radioButtons, process);

}

private JPanel createPane(JRadioButton[] radioButtons,

JButton showButton) {

int numChoices = radioButtons.length;

JPanel box = new JPanel();

box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));

for (int i = 0; i >< numChoices; i++) {

box.add(radioButtons[i]);

}

JPanel pane = new JPanel(new BorderLayout());

pane.add(box, BorderLayout.NORTH);

pane.add(showButton, BorderLayout.SOUTH);

return pane;

}

public void actionPerformed(ActionEvent e) {

String command = group.getSelection().getActionCommand();

//else if button pushed is save

if (command == saveCommand){

// save file

}

//else if button pushed is search by last name

else if (command == sortByLN){

// search by last name

}

//else if button pushed is sort by last name

else if (command == searchLNCommand){

// sort by last name

//print to screen

}

//else if button pushed is display address, ph#, dob

else if (command == printAPD){

// display "search by last name" dialog

//search last names

// if last name found

// print data

// else

// print error notification "person not found"

}

//else if button pushed is list names of people whose

//bday between 2 days

else if (command == printNamesDOB){

// ask for which dates

//search bday

// print to screen

}

//else if button pushed is print names of people between 2 last names

else if (command == printNamesDOB){

// ask for which two last names

//search last names

// if people found

// print to screen

//else

//print error notification "no one found"

}

//else if button pushed is print all family members, friends

//or business associates

else if (command == printPType){

//ask for what person type

//search person types

//if people found

//print to screen

//else print "no one found"

}

}

public class AddressBookEntry{

private extPerson address;

private String date;

private extPerson ExtPerson;

}

/**

* Create the GUI and show it. For thread safety,

* this method should be invoked from the

* event-dispatching thread.

*/

public static void createAndShowGUI(){

JFrame.setDefaultLookAndFeelDecorated(true);

JDialog.setDefaultLookAndFeelDecorated(true);

JFrame frame = new JFrame("Address Book Program");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container c = frame.getContentPane();

c.add(new AddressBook(frame));

frame.pack();

frame.setVisible(true);

}

public static void main (String s[]){

//Schedule a job for the event-dispatching thread:

//creating and showign this application's GUI

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI();

}

});

}

}

//PERSON

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

import java.util.*;

import java.text.SimpleDateFormat;

import java.io.*;

import java.lang.*;

public class Person{

protected String lastName, firstName;

private String address;

private String city;

private String state;

private String zipcode;

private String homephone;

private String extPersonType;

private String bday;

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-DD");

public void parseString(String s) {

try {

lastName = s.substring(0,s.indexOf(","));

firstName = s.substring(s.indexOf(",")+1);

address = s.substring(s.indexOf(",")+2);

city = s.substring(s.indexOf(",")+3);

state = s.substring(s.indexOf(",")+4);

zipcode = s.substring(s.indexOf(",")+5);

homephone = s.substring(s.indexOf(",")+6);

extPersonType = s.substring(s.indexOf(",")+7);

bday = s.substring(s.indexOf(",")+8);

}

catch(StringIndexOutOfBoundsException sbe) {

JOptionPane.showMessageDialog(null,"Error " +

"in Person: Could not parse the line "+s);

}

}

public String toString() {

return lastName+","+firstName+","+address+","+city+","+

state+","+zipcode+","+homephone+","+bday+","+extPersonType;

}

public void setLName(String last) {

lastName=last;

}

public void setFName(String first){

firstName=first;

}

public String getLastName() {

return lastName;

}

public String getFirstName() {

return lastName;

}

public Person() {

lastName="";

firstName="";

}

public Person(String first, String last){

setLName(last);

setFName(first);

}

//Set the address and return it

public void setAddress( String addr ){

address = addr;

}

public String getAddress(){

return address;

}

//set the city and return it

public void setCity( String town ){

city = town;

}

public String getCity(){

return city;

}

//set the state and return it

public void setState( String st )

{

state = st;

}

public String getState()

{

return state;

}

//Set the zip code and return it

public void setZipCode( String zip ){

zipcode = zip;

}

public String getZipCode(){

return zipcode;

}

//Set the home phone and return it

public void setHomePhone( String homeph ){

homephone = homeph;

}

public String getHomePhone(){

return homephone;

}

//Set the bday and return it

public String getBday(){

return bday;

}

public void setBday(String newBday) {

bday = newBday;

dateFormat.format(bday);

}

//Set the extPerson type and return it

public String getPType(){

return extPersonType;

}

public void setPBusiness(){

extPersonType = "Business Associate";

}

public void setPFamily(){

extPersonType = "Family Member";

}

public void setPFriend(){

extPersonType = "Friend";

}

public Person(String data) {

parseString(data);

}

}

//EXTPERSON

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

import java.util.*;

import java.text.SimpleDateFormat;

import java.io.*;

import java.lang.*;

//new clss extPerson

public class extPerson extends Person {

int MAX_PEOPLE=500;

BufferedReader bf;

String lname,fname,street,city,state,zip,phone,persontype,bday;

String FILE_NAME="AddressBook.txt";

public String toString() {

StringBuffer sb=new StringBuffer();

for (int i=0; i<nPeople; i++)

sb=sb.append(group1[i]+"\n");

return sb.toString();

}

public void save() {

try {

PrintWriter pw=new PrintWriter(FILE_NAME);

for (int i=0; i><nPeople; i++)

pw.println(group1[i]+",");

pw.close();

}

catch (FileNotFoundException fne) {

System.out.println("Could not Save "+FILE_NAME);

}

}

public extPerson() {

group1=new extPerson[MAX_PEOPLE];

nPeople=0;

}

public boolean insert(String data) {

if (nPeople><MAX_PEOPLE) {

Person guy = new Person(data);

group1[nPeople]=guy;

nPeople++;

return true;

}

else {

JOptionPane.showMessageDialog(null,"Error in People" +

"::insert: Max size reached.");

return false;

}

}

Person group1[];

int nPeople;

}

>

nichole120 at 2007-7-6 14:34:13 > top of Java-index,Java Essentials,Java Programming...
# 3

> Ok, I have changed my code to reflect your suggested changes,

Well, no you didn't. You're still mixing GUI and app code together in one big ugly mess. You removed storeAddresses, when you probably should have simply renamed it to "loadAddresses".

> but I'm still unsure how to use the findInLine you suggested....

Did you look at the documentation?

paulcw at 2007-7-6 14:34:13 > top of Java-index,Java Essentials,Java Programming...
# 4
Ok, I don't understand what you are saying then.I'm about ready to just scrap this and start all over...
nichole120 at 2007-7-6 14:34:13 > top of Java-index,Java Essentials,Java Programming...
# 5

Here's what you should do:

Write a program that reads the addresses from a file, then prints the number of entries it loaded to the screen using System.out.println. Drive the execution from a test class; the address book functionality will be in classes that can load the file and provide methods on the data, but won't do anything unless those methods are invoked; plus you'll write a test class (with a main() method) that creates instances of those classes, gets the number of addresses found from one of those instances, and prints it.

Then, write test class that loads the addresses and then prints all the entries to the screen, unsorted. (They'll just be printed in the order they were in the addressbook file.)

Then write a test class that loads the addresses, sorts them, and prints them to the screen.

continued...

paulcw at 2007-7-6 14:34:13 > top of Java-index,Java Essentials,Java Programming...
# 6

Then write a test class that does all that, then writes the addresses back to a file unchanged.

Etc. Note that you haven't even began the GUI code yet.

Here's a hint: AddressBookEntry will probably not have a main() method. Here's another hint: AddressBookEntry will probably have a constructor that takes all the entries relevant to an entry -- most notably all the stuff in a single entry in the address book file.

paulcw at 2007-7-6 14:34:13 > top of Java-index,Java Essentials,Java Programming...