#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    1
    Rep Power
    0

    Search Elements in ArrayList


    Hello,

    I am trying to write a method that will compare a String (from user input) to elements in an ArrayList.

    OurExtendedWord(String word, int pos) {
    this.word = word;
    this.pos = pos; }

    class OurList {
    private ArrayList<OurExtendedWord> list;

    OurList() {
    list = new ArrayList<OurExtendedWord>(); }

    /* This is a skeleton for the find() method */
    String find(String word) {
    // Needs to take user input and compare the word to the list
    // If there is a match, return the word and the position
    // If no match, return null
    return null;
    }


    So far, I have:
    String find(String word) {
    // Get user input from Scanner
    String searchFor = input.next();

    // Loop through ArrayList to search for word
    for (OurExtendedWord extWord : list) {
    if (searchFor.equals(extWord)) {
    return extWord.getWord();
    }
    else {
    return null;
    }
    }
    }


    Any ideas on how I can fix this code?
  2. #2
  3. Contributing User
    Devshed Regular (2000 - 2499 posts)

    Join Date
    May 2004
    Location
    Superior, CO, USA
    Posts
    2,418
    Rep Power
    1713
    Perhaps you should wait until you've walked through the entire list before returning null. You'll only compare with the very first element in the ArrayList with your current code.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    74
    Rep Power
    18
    Can you explain what the meaning is of the attribute 'pos' in the object 'OurExtendedWord'? I have an idea what you want to achieve with it, but I'd like to hear it from you because you might want to rethink this design.


    EDIT:

    Repost of http://www.dreamincode.net/forums/topic/311227-search-for-elements-in-arraylist-given-user-input/
    Last edited by Aurum84; February 5th, 2013 at 02:37 PM.
  6. #4
  7. Daniel Schildsky
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Mar 2004
    Location
    KL, Malaysia.
    Posts
    1,555
    Rep Power
    1621

    Problem with the code


    Java Code:
     
    for (OurExtendedWord extWord : list) {
       if (searchFor.equals(extWord)) {
              return extWord.getWord();
       }
       else {
           return null;
       }
    }


    This block of code got 2 problems:
    a) one already mentioned by stdunbar,
    b) You should not be comparing the string searchWord with your extWord, as extWord is an instance of OurExtendedWord instead of a String instance.
    When the programming world turns decent, the real world will turn upside down.

IMN logo majestic logo threadwatch logo seochat tools logo