7 Replies - 406 Views - Last Post: 26 March 2011 - 08:59 PM Rate Topic: -----

#1 jinx3y  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-April 10

Need help Searching Java ArrayList

Posted 25 March 2011 - 08:56 AM

I am not exactly sure how to put this to words, so please bear with me.

I have created an address book GUI for a school project. I am able to input information, and iterate through it as well as delete items in the address book (an arraylist). The input is a colon separated grouping of strings separated by lines in a .txt file (lname:fname:mname:street:city:state:zip:hphone:cphone). The input goes smoothly and I am also to save current arraylist items to an output file. What is added to the list is a grouping of these strings as a <Friend> object.

What I am having trouble doing is searching for jsut the last name and displaying it in the GUI. I have tried indexOf()using a ListIterator but regardless of the input, the value returned by indexOf is always the first index (0).

At this point I am not even sure what the code should look like, bt I know that what needs to happen is that each element of the arraylist needs to be searched to see if it "contains()" the string in question. The question is how?

I am unsure if I should attach my code, but if it helps please let me know and I will be happy to add to a post.

I appreciate any help, thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: Need help Searching Java ArrayList

#2 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1831
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Need help Searching Java ArrayList

Posted 25 March 2011 - 09:21 AM

Maybe an example will help.
Was This Post Helpful? 0
  • +
  • -

#3 Tryparse  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 80
  • View blog
  • Posts: 193
  • Joined: 20-April 10

Re: Need help Searching Java ArrayList

Posted 25 March 2011 - 09:24 AM

If your Friend class is set up in a way that makes sense, a simple for each loop should do the trick:
for (Friend f : friendArrayList){
    if (f.getLastName().equalsIgnoreCase("Smith"))
        guiComponent.setText(f.getLastName());
}

This post has been edited by Tryparse: 25 March 2011 - 09:25 AM

Was This Post Helpful? 2
  • +
  • -

#4 jinx3y  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-April 10

Re: Need help Searching Java ArrayList

Posted 25 March 2011 - 09:49 AM

OK, file input like so:

public void readFromFile(String file) throws FileNotFoundException {
        try {
            Scanner scanner = new Scanner(new File(file));
            while (scanner.hasNextLine()) {
                String[] fields = scanner.nextLine().split(":");
                person = new Person(fields[0],fields[1],fields[2]);
                address = new Address(fields[3],fields[4],fields[5],fields[6]);
                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);
        }
    }



Friend class like so:
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.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();
        setAddress(address);
        sethPhone(hPhone);
        setcPhone(cPhone);

    }



Assume everything else works as it should (GUI, getters/setters - because they do, in fact work)

Add to list method
public void addContact() {
        try {
            String lName = getTxtLastName();
            String mName = getTxtMiddleName();
            String fName = getTxtFirstName();
            String streetName = getTxtStreet();
            String cityName = getTxtCity();
            String stateName = getTxtState();
            String zipCode = getTxtZipCode();
            String hPhone = getTxtHomePhone();
            String cPhone = getTxtCellPhone();
            //CONSTRUCT OBJECTS
            address = new Address(streetName, cityName, stateName, zipCode);
            person = new Person(lName, fName, mName);
            friend = new Friend(person, address, hPhone, cPhone);
            try {
                c.addToList(friend);
                c.setNumContacts();
                getLastContact();
                abg.setHelpText("Contact Added!\n" + abg.toString());
                //entry is added to end of list so, get the last entry and display it
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (getTxtLastName().isEmpty() && (getTxtHomePhone().isEmpty() || getTxtCellPhone().isEmpty())) {
                JOptionPane.showMessageDialog(newFrame,
                        "To add a contact you must at least add\n"
                        + "a Last Name and a Phone Number", "Empty Contact Entry Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        } catch (NullPointerException npe) {
            System.out.println(npe + " while adding a contact in BookActions.addContact() method.");
            npe.printStackTrace();
        } catch (Exception e) {
            System.out.println("Error in BookActions.addContact().");
            e.printStackTrace();
        }
    }




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


this is the problem in question which is only returning the first index

 public void findContact(String search){
        int fndIndex = 0;
        boolean hasSearch = c.contactList.contains(search);
        if(hasSearch){
            fndIndex = c.contactList.indexOf(c.contactList.contains(search));
        }
        System.out.println("B: "+c.contactList.get(fndIndex));
        getContact(fndIndex);
        } 

        }

    }


Was This Post Helpful? 0
  • +
  • -

#5 jinx3y  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-April 10

Re: Need help Searching Java ArrayList

Posted 25 March 2011 - 10:00 AM

View PostTryparse, on 25 March 2011 - 04:24 PM, said:

If your Friend class is set up in a way that makes sense, a simple for each loop should do the trick:
for (Friend f : friendArrayList){
    if (f.getLastName().equalsIgnoreCase("Smith"))
        guiComponent.setText(f.getLastName());
}

This worked, thanks!
    public void findContact(String search) {
        for (Friend f : c.contactList) {
            Address a = f.getAddress();
            if (f.getLName().equalsIgnoreCase(search)) {
                abg.setHelpText(f.getLName());
                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());
            }
        }
    }


Was This Post Helpful? 0
  • +
  • -

#6 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1831
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Need help Searching Java ArrayList

Posted 25 March 2011 - 10:02 AM

Yep, that's probably better...

This post has been edited by r.stiltskin: 25 March 2011 - 10:05 AM

Was This Post Helpful? 0
  • +
  • -

#7 Tryparse  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 80
  • View blog
  • Posts: 193
  • Joined: 20-April 10

Re: Need help Searching Java ArrayList

Posted 26 March 2011 - 08:36 PM

A quick point about efficiency .. you're assigning a value to "a" (not to mention re-declaring "a") on every iteration of the loop, when you don't actually need that value unless the if condition is true. It would be better to do:
for (Friend f : c.contactList) {
	        if (f.getLName().equalsIgnoreCase(search)) {
	            Address a = f.getAddress();
	            abg.setHelpText(f.getLName());
                    ...

This way, you're only getting that address value when you actually need it, and therefore making the computer do less work. Admittedly, on a project of this scale, you're never going to see a performance difference, but keeping little things like this in mind can be very beneficial when doing much larger projects.
Was This Post Helpful? 2
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8024
  • View blog
  • Posts: 31,149
  • Joined: 06-March 08

Re: Need help Searching Java ArrayList

Posted 26 March 2011 - 08:59 PM

Tryparse change your signature :)
You shouldn't compare String using ==... equals() would be more appropriate
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1