Link to home
Start Free TrialLog in
Avatar of g_currier
g_currierFlag for Germany

asked on

Problems with file input to arraylist

I know that the file I am using can be read by the methods I am using.  The problem I am now having is the contructors (I believe).

After loading the sample data (through the GUI), I request the first record and get only one contact - and that contact is the LAST contact with ONLY the Person object displayed (the rest of the fields are null.

In a nutshell, only one contact from the entire file is loaded.

Here are test results using only the method and a runner to test input

modification for testing (ContactBook.readFromFile(file)

public void readFromFile(String file) throws FileNotFoundException {
        try {
            Scanner scanner = new Scanner(new File(file));
            while (scanner.hasNextLine()) {
                String[] fields = scanner.nextLine().split(":");
//                address = new Address(fields[3],fields[4],fields[5],fields[6]);
//                person = new Person(fields[0],fields[1],fields[2]);
//                friend = new Friend(person, address, fields[7],fields[8]);
                String line = fields[0].toString()+", "+fields[1].toString()+" "+fields[2].toString()+" "+
                        fields[3].toString()+", "+fields[4].toString()+", "+fields[5].toString()+" "+fields[6].toString()+" "+
                        fields[7].toString()+" "+fields[8].toString()+" ";
                System.out.println(line);
            }
            scanner.close();
//            addToList(friend);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ContactBook.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Open in new window

Output from reading the file and printing to console:
run:
Last, First MI Street, City, State ZipCode HomePhone CellPhone 
Anderson, Robert M. 19 AnyStreet, AnyCity, AnyTown 12345 (123)456-7890 (987)654-3210 
MacLean, Jerry A. 34th Ave West, #12, Brooklyn, NY 66978 (447)582-9943 (447)221-7735 
LastName, First MI Street, City, State ZipCode HomePhone CellPhone 
Macintosh, Jerry A. 34th Ave West, #12, Brooklyn, NY 66978 (447)582-9943 (447)221-7735 
LName, First MI Street, City, State ZipCode HomePhone CellPhone 
Macgregor, Jerry A. 34th Ave West, #12, Brooklyn, NY 66978 (447)582-9943 (447)221-7735 
TestLast, First MI Street, City, State ZipCode HomePhone CellPhone 
Sherman, Jerry A. 34th Ave West, #12, Brooklyn, NY 66978 (447)582-9943 (447)221-7735 
Shrew, Lucretia W. 44 inches underground, farmers field, KS 55768 none none 
BUILD SUCCESSFUL (total time: 0 seconds)

Open in new window


Runner
package P4.v2_4;

import java.io.FileNotFoundException;

public class AddressBook {

    public static void main(String[] args) throws FileNotFoundException {
//        new AddressBookGUI();
        ContactBook c = new ContactBook();
        c.readFromFile("input.txt");
    }
}

Open in new window


Using the GUI to load the data nets the results problem of only one contact being loaded and of that contact, only the person object is added.
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You're using the wrong delimiter for that file. It should be
String[] fields = scanner.nextLine().split("\\s*,\\s*");

Open in new window

Avatar of g_currier

ASKER

I'll try that.

 I found part of the problem however.  I moved the addToList() method within the loop and all contacts from the list were added.  However, the addresses are still not part the contact object.
that was the output, the input file is still colon delimited (i added the commas to the output for clarity only...
Why are those lines commented out in your code?
Here are the Person, Friend and Address classes (revised)
person class
package P4.v2_4;

public class Person{

    public String lName,fName,mName;

    public Person(){
    }

    public Person(Person person){
        this.fName = person.getFName();
        this.lName = person.getLName();
        this.mName = person.getMName();
    }

    public Person(String lName, String fName, String mName) {
        setLName(lName);
        setFName(fName);
        setMName(mName);
    }

    public String getFName() {
        return fName;
    }

    public String getLName() {
        return lName;
    }

    public String getMName() {
        return mName;
    }

    public void setFName(String fName) {
        this.fName = fName;
    }

    public void setLName(String lName) {
        this.lName = lName;
    }

    public void setMName(String mName) {
        this.mName = mName;
    }

    public String getFullNameString() {
        return lName + "," + fName + " " + mName+"\n";
    }

    @Override
    public String toString() {
        return lName + ":" + fName + ":" + mName;
    }
}

Open in new window

friend class
package P4.v2_4;

public class Friend extends Person {

    public String hPhone, cPhone;
    public Address a = new Address();

    public Friend() {
    }

    public Friend(Person person, Address address) {
        super.lName = person.getLName();
        super.fName = person.getFName();
        super.mName = person.getMName();
        a.streetName = a.getStreetName();
        a.cityName = a.getCityName();
        a.stateName = a.getStateName();
//        a.setAddress(address);
        a.zipCode = a.getZipCode();
    }

    public Friend(String hPhone, String cPhone) {
        sethPhone(hPhone);
        setcPhone(cPhone);
    }

    public Friend(Person person, Address address, String hPhone, String cPhone) {
        super.lName = person.getLName();
        super.fName = person.getFName();
        super.mName = person.getMName();
        a.streetName = a.getStreetName();
        a.cityName = a.getCityName();
        a.stateName = a.getStateName();
        a.zipCode = a.getZipCode();
        sethPhone(hPhone);
        setcPhone(cPhone);

    }

    public String getcPhone() {
        return cPhone;
    }

    public void setcPhone(String cPhone) {
        this.cPhone = cPhone;
    }

    public String gethPhone() {
        return hPhone;
    }

    public void sethPhone(String hPhone) {
        this.hPhone = hPhone;
    }

    public String getFriendString() {
        return getFullNameString() + "\n"
                + a.toString() + "\n"
                + "Home: " + hPhone + "\n"
                + "Mobile:  " + cPhone + "\n";

    }

    @Override
    public String toString() {
        return lName + ":" + fName + ":" + mName + ":" + a.toString() + ":" + hPhone + ":" + cPhone;

    }
}

Open in new window


address class
package P4.v2_4;

public class Address {

    public String streetName, cityName, stateName, zipCode;

    private Address address;

    public Address() {
    }

    public Address(Address address) {
        this.streetName = address.getStreetName();
        this.cityName = address.getCityName();
        this.stateName = address.getCityName();
        this.zipCode = address.getZipCode();
    }

    public Address(String streetName, String cityName, String stateName, String zipCode) {
        setStreetName(streetName);
        setCityName(cityName);
        setStateName(stateName);
        setZipCode(zipCode);
    }

    public Address getAddress(){
        return address;
    }

    public void setAddress(Address address){
        this.address = address;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getStateName() {
        return stateName;
    }

    public void setStateName(String stateName) {
        this.stateName = stateName;
    }

    public String getStreetName() {
        return streetName;
    }

    public void setStreetName(String streetName) {
        this.streetName = streetName;
    }

    public String getZipCode() {
        return zipCode;
    }

    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }

    @Override
    public String toString() {
        return streetName + ":" + cityName + ":" + stateName + ":" + zipCode;
    }

    


}

Open in new window


nothing else has changed from the other classes (except the readFromFile method in ContactBook)
The code in the first message was what I used to test the input (I wanted to see the output on the console to make sure the entir file was read correctly (have some wierd issues with notepad adding hidden carriage return/linefeeds - this was a way to check the cr/lf were in the right places).  This would make sure the scanner wouldn't throw an error at an empty line or find the wrong input in the wrong field.  Testing only (that's why the code is commented out)  It is in use now and all contacts (minus addresses) are fed in to the arraylist.
Only use say 2 lines in the input file and use a different editor. Start with a new file and user WordPad (Start|Run|Write)
ok
(No copy/paste from the previous file)
Ok, no more problems with cr/lf.  Why is the Address portion not being fed in?
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I spotted that earlier and changed it accordingly, but the results are still the same.  I'm pretty sure I did something wrong with the Address class or the friend class:

readFromFile():
 
public void readFromFile(String file) throws FileNotFoundException {
        try {
            Scanner scanner = new Scanner(new File(file));
            while (scanner.hasNextLine()) {
                String[] fields = scanner.nextLine().split(":");
                address = new Address(fields[3],fields[4],fields[5],fields[6]);
                person = new Person(fields[0],fields[1],fields[2]);
                friend = new Friend(person, address, fields[7],fields[8]);
                addToList(friend);
            }
            scanner.close();
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ContactBook.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Open in new window


Friend Class
package P4.v2_4;

public class Friend extends Person {

    public String hPhone, cPhone;
    public Address a = new Address();

    public Friend() {
    }

    public Friend(Person person, Address address) {
        super.lName = person.getLName();
        super.fName = person.getFName();
        super.mName = person.getMName();
        a.streetName = a.getStreetName();
        a.cityName = a.getCityName();
        a.stateName = a.getStateName();
//        a.setAddress(address);
        a.zipCode = a.getZipCode();
    }

    public Friend(String hPhone, String cPhone) {
        sethPhone(hPhone);
        setcPhone(cPhone);
    }

    public Friend(Person person, Address address, String hPhone, String cPhone) {
        super.lName = person.getLName();
        super.fName = person.getFName();
        super.mName = person.getMName();
        a.streetName = a.getStreetName();
        a.cityName = a.getCityName();
        a.stateName = a.getStateName();
        a.zipCode = a.getZipCode();
        sethPhone(hPhone);
        setcPhone(cPhone);

    }

    public String getcPhone() {
        return cPhone;
    }

    public void setcPhone(String cPhone) {
        this.cPhone = cPhone;
    }

    public String gethPhone() {
        return hPhone;
    }

    public void sethPhone(String hPhone) {
        this.hPhone = hPhone;
    }

    public String getFriendString() {
        return getFullNameString() + "\n"
                + a.toString() + "\n"
                + "Home: " + hPhone + "\n"
                + "Mobile:  " + cPhone + "\n";
    }

    @Override
    public String toString() {
        return lName + ":" + fName + ":" + mName + ":" + a.toString() + ":" + hPhone + ":" + cPhone;

    }
}

Open in new window


Address Class:
 
package P4.v2_4;

public class Address {

    public String streetName, cityName, stateName, zipCode;

//    private Address address;

    public Address() {
    }

    public Address(Address address) {
        this.streetName = address.getStreetName();
        this.cityName = address.getCityName();
        this.stateName = address.getCityName();
        this.zipCode = address.getZipCode();
    }

    public Address(String streetName, String cityName, String stateName, String zipCode) {
        setStreetName(streetName);
        setCityName(cityName);
        setStateName(stateName);
        setZipCode(zipCode);
    }

//    public Address getAddress(){
//        return address;
//    }

//    public void setAddress(Address address){
//        this.address = address;
//    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getStateName() {
        return stateName;
    }

    public void setStateName(String stateName) {
        this.stateName = stateName;
    }

    public String getStreetName() {
        return streetName;
    }

    public void setStreetName(String streetName) {
        this.streetName = streetName;
    }

    public String getZipCode() {
        return zipCode;
    }

    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }

    @Override
    public String toString() {
        return streetName + ":" + cityName + ":" + stateName + ":" + zipCode;
    }
}

Open in new window

problem could be elsewhere in your code
whats addToList() do
and what returns the first contact
You need to create new instances in the loop
Address address = new Address(fields[3],fields[4],fields[5],fields[6]);// Same for other two objects' creation

Open in new window

addToList():
 
public void addToList(Friend friend) {
        this.contactList.add(friend);
        setNumContacts();
    }

Open in new window


getFirstContact():
 
public void getFirstContact() {
        if (c.isListEmpty()) {
            abg.setHelpText("There are no contacts in the Address Book.\n"
                    + "Please choose \"Load Sample Contacts\" or\n"
                    + "\"Load Saved Data\" from the \"Edit\" menu.");
        } else {
            iterate = 0;
            ListIterator itr = c.contactList.listIterator(start);
            String line = itr.next().toString();
            Scanner scan = new Scanner(line);
            while (scan.hasNext()) {
                String[] fields = scan.next().split(":");
                abg.setLastName(fields[0]);
                abg.setFirstName(fields[1]);
                abg.setMiddleName(fields[2]);
                abg.setStreetName(fields[3]);
                abg.setCityName(fields[4]);
                abg.setStateName(fields[5]);
                abg.setZipCode(fields[6]);
                abg.setHomePhone(fields[7]);
                abg.setCellPhone(fields[8]);
            }
            scan.close();
            abg.setHelpText("Size of list: " + (c.getSize()) + "\nList index number: " + iterate + "\n\n" + abg.toString());
        }
    }

Open in new window

you can just get the friend from the list directly

Friend friend = contactList.get(0);

(assuming contactList is List<Friend>)

No need to convert to a string and parse
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
that stilldoes not make the address fields available

 
public void getFirstContact() {
        if (c.isListEmpty()) {
            abg.setHelpText("There are no contacts in the Address Book.\n"
                    + "Please choose \"Load Sample Contacts\" or\n"
                    + "\"Load Saved Data\" from the \"Edit\" menu.");
        } else {
            Friend f = c.getContact(start);
            abg.setLastName(f.getLName());
            abg.setFirstName(f.getFName());
            abg.setMiddleName(f.getMName());
            abg.setCellPhone(f.getcPhone());
            abg.setHomePhone(f.gethPhone());
            abg.setHelpText("Size of list: " + (c.getSize()) + "\nList index number: " + iterate + "\n\n" + abg.toString());

        }
    }

Open in new window


but it does allow setting the text fields in the GUI.  But the friend Constructor has to be incorrect because I do not have a way to access the address from Friend (I think that's what it is)
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Something like this? (though it doesn't work)

Friend class
 
public Friend(Person person, Address address, String hPhone, String cPhone) {
        super.lName = person.getLName();
        super.fName = person.getFName();
        super.mName = person.getMName();
//        a.streetName = a.getStreetName();
//        a.cityName = a.getCityName();
//        a.stateName = a.getStateName();
//        a.zipCode = a.getZipCode();
        setAddress(a);
        sethPhone(hPhone);
        setcPhone(cPhone);

    }

    public Address getAddress(){
        return a;
    }

    public void setAddress(Address address){
        address.setStreetName(a.streetName);
        address.setCityName(a.cityName);
        address.setStateName(a.stateName);
        address.setZipCode(a.zipCode);
    }

Open in new window

getFirstContact()
 
public Friend(Person person, Address address, String hPhone, String cPhone) {
        super.lName = person.getLName();
        super.fName = person.getFName();
        super.mName = person.getMName();
//        a.streetName = a.getStreetName();
//        a.cityName = a.getCityName();
//        a.stateName = a.getStateName();
//        a.zipCode = a.getZipCode();
        setAddress(a);
        sethPhone(hPhone);
        setcPhone(cPhone);

    }

    public Address getAddress(){
        return a;
    }

    public void setAddress(Address address){
        address.setStreetName(a.streetName);
        address.setCityName(a.cityName);
        address.setStateName(a.stateName);
        address.setZipCode(a.zipCode);
    }

Open in new window

public void getFirstContact() {
        if (c.isListEmpty()) {
            abg.setHelpText("There are no contacts in the Address Book.\n"
                    + "Please choose \"Load Sample Contacts\" or\n"
                    + "\"Load Saved Data\" from the \"Edit\" menu.");
        } else {
            Friend f = c.getContact(start);
            Address a = f.getAddress();
            abg.setLastName(f.getLName());
            abg.setFirstName(f.getFName());
            abg.setMiddleName(f.getMName());
            abg.setStreetName(a.getStreetName());
            abg.setCityName(a.getCityName());
            abg.setStateName(a.getStreetName());
            abg.setZipCode(a.getZipCode());
            abg.setCellPhone(f.getcPhone());
            abg.setHomePhone(f.gethPhone());
            abg.setHelpText("Size of list: " + (c.getSize()) + "\nList index number: " + iterate + "\n\n" + abg.toString());

        }
    }

Open in new window

Did you make the three alterations i mentioned?
Sorry, got the parameters backward:
 
public Friend(Person person, Address address, String hPhone, String cPhone) {
        super.lName = person.getLName();
        super.fName = person.getFName();
        super.mName = person.getMName();
//        a.streetName = a.getStreetName();
//        a.cityName = a.getCityName();
//        a.stateName = a.getStateName();
//        a.zipCode = a.getZipCode();
        setAddress(address);
        sethPhone(hPhone);
        setcPhone(cPhone);

    }

    public Address getAddress(){
        return a;
    }

    public void setAddress(Address address){
        a.setStreetName(address.streetName);
        a.setCityName(address.cityName);
        a.setStateName(address.stateName);
        a.setZipCode(address.zipCode);
    }

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Is getContact() returning the correct contact?
I did, but then everything diplayed was "null".  With the changed Friend constructor everyhting diplays "out of sync" (friend vs. address)
getting the first contact with both sets of changes, returns blank text fields (nothing is being set).

reverting back to the old readFromFile allows fileds to be set but the address and friend objects do not correspond
(when iterating)
> reverting back to the old readFromFile

you shouldn't have need to change that at all (except for moving addToList() inside the loop)

suspect your problem is with getContact()

> (when iterating)

you shouldn't need to iterate at all
Don't make unnecessary changes. That will just lead to problems spiralling. This was your problem:

>>I request the first record and get only one contact - and that contact is the LAST contact

I've just told you how to solve that
This is what works:

readFromFile():
public void readFromFile(String file) throws FileNotFoundException {
        try {
            Scanner scanner = new Scanner(new File(file));
            while (scanner.hasNextLine()) {
                String[] fields = scanner.nextLine().split(":");
//                Address a = new Address(fields[3],fields[4],fields[5],fields[6]);
//                Person p = new Person(fields[0],fields[1],fields[2]);
//                Friend f = new Friend(person, address, fields[7],fields[8]);
                address = new Address(fields[3],fields[4],fields[5],fields[6]);
                person = new Person(fields[0],fields[1],fields[2]);
                friend = new Friend(person, address, fields[7],fields[8]);
                addToList(friend);
                //Testing
//                String line = fields[0].toString()+", "+fields[1].toString()+" "+fields[2].toString()+" "+
//                        fields[3].toString()+", "+fields[4].toString()+", "+fields[5].toString()+" "+fields[6].toString()+" "+
//                        fields[7].toString()+" "+fields[8].toString()+" ";
//                System.out.println(line);
               
            }
            scanner.close();
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ContactBook.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Open in new window


list "iteration":
public void getFirstContact() {
        iterate = start;
        if (c.isListEmpty()) {
            abg.setHelpText("There are no contacts in the Address Book.\n"
                    + "Please choose \"Load Sample Contacts\" or\n"
                    + "\"Load Saved Data\" from the \"Edit\" menu before iterating through the list.");
        } else {
            Friend f = c.getContact(start);
            Address a = f.getAddress();
            abg.setLastName(f.getLName());
            abg.setFirstName(f.getFName());
            abg.setMiddleName(f.getMName());
            abg.setStreetName(a.getStreetName());
            abg.setCityName(a.getCityName());
            abg.setStateName(a.getStreetName());
            abg.setZipCode(a.getZipCode());
            abg.setCellPhone(f.getcPhone());
            abg.setHomePhone(f.gethPhone());
            abg.setHelpText("Size of list: " + (c.getSize()) + "\nList index number: " + iterate + "\n\n" + abg.toString());
            abg.setHelpText("Size of list: " + (c.getSize()) + "\nList index number: " + iterate + "\n\n" + abg.toString());

        }
    }

    public void getNextContact() {
        if (c.isListEmpty()) {
            abg.setHelpText("There are no contacts in the Address Book.\n"
                    + "Please choose \"Load Sample Contacts\" or\n"
                    + "\"Load Saved Data\" from the \"Edit\" menu before iterating through the list.");
        } else {
            Friend f = c.getContact(iterate);
            Address a = f.getAddress();
            abg.setLastName(f.getLName());
            abg.setFirstName(f.getFName());
            abg.setMiddleName(f.getMName());
            abg.setStreetName(a.getStreetName());
            abg.setCityName(a.getCityName());
            abg.setStateName(a.getStreetName());
            abg.setZipCode(a.getZipCode());
            abg.setCellPhone(f.getcPhone());
            abg.setHomePhone(f.gethPhone());
            abg.setHelpText("Size of list: " + (c.getSize()) + "\nList index number: " + iterate + "\n\n" + abg.toString());
            iterate++;
        }
        abg.setHelpText("Size of list: " + (c.getSize()) + "\nList index number: " + iterate + "\n\n" + abg.toString());
    }

    public void getPreviousContact() {
        if (c.isListEmpty()) {
            abg.setHelpText("There are no contacts in the Address Book.\n"
                    + "Please choose \"Load Sample Contacts\" or\n"
                    + "\"Load Saved Data\" from the \"Edit\" menu before iterating through the list.");
        } else {
            Friend f = c.getContact(iterate);
            Address a = f.getAddress();
            abg.setLastName(f.getLName());
            abg.setFirstName(f.getFName());
            abg.setMiddleName(f.getMName());
            abg.setStreetName(a.getStreetName());
            abg.setCityName(a.getCityName());
            abg.setStateName(a.getStreetName());
            abg.setZipCode(a.getZipCode());
            abg.setCellPhone(f.getcPhone());
            abg.setHomePhone(f.gethPhone());
            abg.setHelpText("Size of list: " + (c.getSize()) + "\nList index number: " + iterate + "\n\n" + abg.toString());
            iterate--;
        }
        abg.setHelpText("Size of list: " + (c.getSize()) + "\nList index number: " + iterate + "\n\n" + abg.toString());

    }

    public void getLastContact() {
        iterate = c.getSize()-1;
        if (c.isListEmpty()) {
            abg.setHelpText("There are no contacts in the Address Book.\n"
                    + "Please choose \"Load Sample Contacts\" or\n"
                    + "\"Load Saved Data\" from the \"Edit\" menu before iterating through the list.");
        } else {
            Friend f = c.getContact(c.getSize()-1);
            Address a = f.getAddress();
            abg.setLastName(f.getLName());
            abg.setFirstName(f.getFName());
            abg.setMiddleName(f.getMName());
            abg.setStreetName(a.getStreetName());
            abg.setCityName(a.getCityName());
            abg.setStateName(a.getStreetName());
            abg.setZipCode(a.getZipCode());
            abg.setCellPhone(f.getcPhone());
            abg.setHomePhone(f.gethPhone());
            abg.setHelpText("Size of list: " + (c.getSize()) + "\nList index number: " + iterate + "\n\n" + abg.toString());

        }
        abg.setHelpText("Size of list: " + (c.getSize()) + "\nList index number: " + iterate + "\n\n" + abg.toString());
    }

Open in new window


I still have to work out how to accurately reflect which index is showing and catch the IndexOutOfBoundsException (when trying to get the previous or next at either end of the list).

It now displays each contact in order from first to last (the ListIterator was giving me a headache anyway).
I mentioned in your other question how to do next/previous

Thanks for the advice and suggestions
You can check the current index before getting element from list to avoid exception
Of course, I'm forgetting the simple things now...lol.  I've been working at this for too many hours straight.