Results 1 to 19 of 19
  1. #1
    spleenlol is offline Member
    Join Date
    Feb 2010
    Posts
    11
    Rep Power
    0

    Default Search ArrayList

    Hey everyone. I'm relatively new to the forum. I am working on this quick little program. I want to have the user type in some text and then store that input into an ArrayList. Once they are done entering data then it prompts them to see if they want to search the ArrayList using a substring they type in. So if these were the past strings entered:
    I went to the park last night.
    Do you want to park your car over there?
    I like eating pizza after work.

    If I entered: park then I should only get the first two results back. I'm not very good at substrings and I was wondering if someone could point me in the right direction. Thanks so much. Here is my code so far:
    Java Code:
    public static void enterText(String txtIn)
        {
            Scanner in = new Scanner(System.in);
            System.out.print("Would you like to enter more text? Please answer Y or N: ");
            String input = in.nextLine();
          
            if (input.equals("Y"))
            {
                arrayList(txtIn);
            }
            else if (input.equals("N"))
            {
                searchArray(txtIn);
            }
            else
            {
                System.out.println("You didn't enter Y or N.");
                enterText(txtIn);
            }
        }
        public static void searchArray(String txtIn)
        {
            //add code to search for text
            
        }
    
        public static void searchArrayPrompt(String txtIn)
        {
             System.out.print("Would you like to search for text? Enter Y or N:");
                Scanner in = new Scanner(System.in);
                String input = in.nextLine();
                
                if (input.equals("Y") || input.equals("y"))
                {
                    searchArray(txtIn);   
                }
                else if (input.equals("N") || input.equals("n"))
                {
                    System.out.println("Okay see you!");
                }
                else
                {
                    System.out.println("You didn't enter Y or N.");
                    searchArrayPrompt(txtIn);
                }
        }
        public static void arrayList(String txtIn)
        {
            Scanner in = new Scanner(System.in);
            System.out.print("Enter a string of text: ");
            String input = in.nextLine();
    
            ArrayList al = new ArrayList();
            al.add(input);
            searchArrayPrompt(txtIn);
    
        }
        public static void addStringArray(String txtIn)
        {
            System.out.print("Would you like to add strings to an array? Y or N: ");
            Scanner in = new Scanner(System.in);
            String input = in.nextLine();
            
            if (input.equals("Y") || input.equals("y"))
            {
                arrayList(txtIn);
            }
            else if (input.equals("N") || input.equals("n"))
            {
                System.out.println("Okay see you!");
            }
            else
            {
                System.out.println("You didn't enter Y or N.");
                addStringArray(txtIn);
            }
        }
        
        public static void main(String[] args) 
        {
          
            //questions(input)
            addStringArray(null);
        }
    The
    Java Code:
    //add code to search for array
    is where I am currently. I'm not sure really what to do with the substrings or how even to implement them. Thanks everyone.

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    The following little method checks whether or not a String str is a substring of element i of a List:

    Java Code:
    boolean isSubstring(List<String> list, int i, String str) {
       list.get(i).indexOf(str) >= 0;
    }
    kind regards,

    Jos

  3. #3
    spleenlol is offline Member
    Join Date
    Feb 2010
    Posts
    11
    Rep Power
    0

    Default

    I tried that code but it says that it is not a statement when I put it in. Am I doing something wrong?:confused:

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by spleenlol View Post
    I tried that code but it says that it is not a statement when I put it in. Am I doing something wrong?:confused:
    Obviously, yes. What, we have no idea unless you show us how you are trying to use it.

  5. #5
    spleenlol is offline Member
    Join Date
    Feb 2010
    Posts
    11
    Rep Power
    0

    Default

    Well I replaced the searchArray method and tried to replace it with the method that was given:

    Java Code:
     public static void enterText(String txtIn)
        {
            Scanner in = new Scanner(System.in);
            System.out.print("Would you like to enter more text? Please answer Y or N: ");
            String input = in.nextLine();
          
            if (input.equals("Y"))
            {
                arrayList(txtIn);
            }
            else if (input.equals("N"))
            {
                searchArray(txtIn);  -------getting error here
            }
            else
            {
                System.out.println("You didn't enter Y or N.");
                enterText(txtIn);
            }
        }
        //public static void searchArray(String txtIn)
        //{
           boolean searchArray(List<String> list, int i, String str) {  ---error here
                list.get(i).indexOf(str);  -----error here
            //}
    
        }
    On the first error it says that the method cannot be applied to given types. I'm pretty sure it's because the searchArray method has 3 parameters and the other one only has one given. In the searchArray it has missing return statement. I put a return true in there and now the only error is on:
    Java Code:
    searchArray(txtIn);

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    A couple of comments and thoughts:

    1) Is this a school assignment? If so, what are your specific requirements? What code have you been given and need to work with? This is important since the answers to most questions will often change depending on the requirments.

    2) You probably shouldn't name methods or variables the same name as a class in the Java library. For instance your arrayList(...) method is confusing, at least it is to me. It also should be named for what it does, and this name, arrayList, is far too general, too non-specific.

    3) You're either going to have to create an ArrayList class variable or you're going to have to pass the arraylist to any method that wants to use it.

    4) If you want to loop through the array list, looking at each string in the array list, you'll need to use a loop such as a for loop (or the foreach variant). I don't see one in your code as yet.

    5) You may not be able to use Jos's code as written in your own program, but hopefully you can use his ideas to create your own method that does the same or similar things.

    Much luck!

  7. #7
    spleenlol is offline Member
    Join Date
    Feb 2010
    Posts
    11
    Rep Power
    0

    Default

    Yeah it's a school assignment. Here are some of the requirements:
    Goals
    The goal of this lab is the storage of objects in a collection. In this case it is a simple ArrayList.
    You will start with your program from Lab3 and extend it.
    Speci cations
    As the user types in the text strings, you must save them in an ArrayList. A new option that the
    user will have is the ability to recall past strings by searching for them. At each menu, the user
    will be given the option to get a stored text string. Since they probably will not remember the
    total text of the strings entered, they can enter a substring to search. If a text string exists with
    the entered substring included, all text string options must be listed and then the user can choose
    the one they want to use.
    For example:
    If there were past strings entered:
    Four score and seven years ago...
    The score of the game is 28-10.
    I am the king of the world.
    And the user entered core
    The fi rst two strings will be shown to the user to choose. When the user chooses one of the text
    strings, that text will be available for the operations which already exist in your program, from
    Lab3

    I have the code for the lab3 but it shouldn't really be relevant. Because all I need to do is search for the string in the arraylist then pick which one to use and use that string on my parts for lab3. If you wish to see lab3 you may however I just need to focus on getting the string out of the arraylist.

    I was thinking of a for loop to get the substring. I think it would be something to the effect of: looping from 0 -> end of the last index number in the arraylist and have it spit out all occurences of the data that it finds.

    Basically what the arrayList method that I created does is it prompts the user for some code and then puts that into the arraylist.

  8. #8
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    My bad;I forgot a return statement:

    Java Code:
    boolean isSubstring(List<String> list, int i, String str) {
       return list.get(i).indexOf(str) >= 0;
    }
    You pass in a list of Strings, an index and a substring; the method figures out if str is a substring of the i-th element of the list.

    kind regards,

    Jos

  9. #9
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Please, JosAH, couldn't you have hinted at it, and why are you changing the function params? You're a senior member, and you're giving out incorrect solutions - bad enough to give out solutions in the first place, but PLEASE, don't give out solutions that cause errors - they have to figure out what the code does in the first place, let alone read through the errors to know what is supposed to happen.

    @OP:
    Easier to use a static member variable as an arraylist- or make it all non-static, but for now we'll stick to static, since it works for the assignment - in the future, avoid static things that aren't a: factory methods, B: constants for method calls, or C: private static variables used to identify objects/create unique properties
    (If the above doesn't make sense to you, ignore it, but remember it - it might come in handy)

    then, in your search method, use an iterator loop (E var:Iterable<E> iterate) and String.contains(CharSequence s) inside it, return true if(String.contains(searchFor)) (A string is a CharSequence,along with a StringBuffer and other classes - confused me for a while when I saw that for the first time!)

    The reason for all this is that you seem to be creating an ArrayList<String> in arrayList and then dropping it! It looks to me at this point like poorly written C code, that forgets parameters... BAD BAD BAD - your program will not do what you want, and C coding styles DO NOT work in Java (nor vice versa, as I have learned!) Use a static variable for this case, since it is written for it, but REALLY, SERIOUSLY use instance member variables (non-static variables) in the future.

    @Jos: Sorry if I sounded harsh. I've taught myself Java,C,C++,PHP,and Python within a year and a half, and get sensitive when people give out solutions. It doesn't teach people what the code does, and why it works, it just gives them a solution. Thats why I spent the first 3 weeks of learning to program trying to figure out what REUSABLE code was, WHY my ImageIcon that I reassigned didn't generate 2 images, and WTH a method was, and why I could write the same constructor twice and get two different things. Because people gave me solution, not direction. I'd personally prefer not to solve every salaried programmer's problem for him because he was always given the solution. (As you can see, I'm VERY touchy about this!)

    I'm also very tired - too many long nights trying to get projects done before the olympics - be glad they're not in your city - so I apologize if I'm incomprehensible and irritable
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  10. #10
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Singing Boyo View Post
    Please, JosAH, couldn't you have hinted at it, and why are you changing the function params? You're a senior member, and you're giving out incorrect solutions - bad enough to give out solutions in the first place, but PLEASE, don't give out solutions that cause errors - they have to figure out what the code does in the first place, let alone read through the errors to know what is supposed to happen.
    I didn't change the parameters for that little method; all I did was put a 'return' statement in because I forgot it in my first reply. I consider that method a hint, not a full blown solution. Please show me the error in my code.

    kind regards,

    Jos

  11. #11
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    The OP's method signature:

    Java Code:
        public static void searchArray(String txtIn)
        {
            //add code to search for text
            
        }
    your code:
    Java Code:
    boolean isSubstring(List<String> list, int i, String str) {
       return list.get(i).indexOf(str) >= 0;
    }
    You added two parameters, which reasonably should be there, but his method didn't have them. And it looks even more like C code than his does. If he tried to put that it and had it called from a different class, something would break...

    And it may not be quite a full-blown solution, but it's definitely close.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  12. #12
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    6

    Default

    All the op had to do was loop through the strings in his array list and if isSubstring(list, i, "core") returned true, print list.get(i); I think josah gave a giant hint and would've completely answered the op's question on how to search an array list if the op actually knew what parameters of a function meant.

  13. #13
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Yes... and it makes me curious to know what they are teaching in classes these days. It seems I learned more on my own in 2 months than students learn in a year - and I'm in grade 10! Really scares me to think that I'll know more than my prof will!
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  14. #14
    spleenlol is offline Member
    Join Date
    Feb 2010
    Posts
    11
    Rep Power
    0

    Default

    We haven't learned about parameters yet. I've only been in class doing this for a month. The first month was mostly review of C# commands and other things. I think I know what to do and will work on it probably later this week because I have exams. I'll update hopefully by tomorrow friday at the latest of something that I tried. Because I'm pretty sure I know what I need to do. I took out JosAH's code and I'll work on something that I have in mind. Thanks everyone! I'll post back before friday sometime hopefully :)

  15. #15
    spleenlol is offline Member
    Join Date
    Feb 2010
    Posts
    11
    Rep Power
    0

    Default

    So I worked on it a little bit and I think I'm almost there. Here is what I have so far:
    Java Code:
     public static void arrayList(String txtIn)
        {
            Scanner in = new Scanner(System.in);
            System.out.print("Enter a string of text: ");
            String input = in.nextLine();
    
            ArrayList<String> al = new ArrayList<String>();
            al.add(input);
             Scanner in2 = new Scanner(System.in);
            System.out.print("Would you like to enter more text? Please answer Y or N: ");
            String input2 = in2.nextLine();
          
            if (input2.equals("Y") || input2.equals("y"))
            {
                arrayList(txtIn);
            }
            else if (input2.equals("N") || input2.equals("n"))
            {
                Scanner in3 = new Scanner(System.in);
                System.out.print("Enter a substring to search: ");
                String input3 = in3.nextLine();
                for (int i=0;i<al.size();i++)
                     {
                        System.out.println(al.get(i).indexOf(input3));
                     }
            }
            else
            {
                System.out.println("You didn't enter Y or N.");
            }
    
        }
        public static void addStringArray(String txtIn)
        {
            System.out.print("Would you like to add strings to an array? Y or N: ");
            Scanner in = new Scanner(System.in);
            String input = in.nextLine();
            
            if (input.equals("Y") || input.equals("y"))
            {
                arrayList(txtIn);
            }
            else if (input.equals("N") || input.equals("n"))
            {
                System.out.println("Okay see you!");
            }
            else
            {
                System.out.println("You didn't enter Y or N.");
                addStringArray(txtIn);
            }
        }
        
        public static void main(String[] args) 
        {
          
            addStringArray(null);
        }
    I tried to run this and here is the output that I am getting. I think it has something to do with the arrayList because it's putting out a number and not a string.
    Java Code:
    Would you like to add strings to an array? Y or N: y
    Enter a string of text: i am a man
    Would you like to enter more text? Please answer Y or N: y
    Enter a string of text: oh man am i cool
    Would you like to enter more text? Please answer Y or N: y
    Enter a string of text: that woman is a man
    Would you like to enter more text? Please answer Y or N: n
    Enter a substring to search: man
    7
    BUILD SUCCESSFUL (total time: 16 seconds)
    Thanks guys sorry for all the trouble.

  16. #16
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    you are still using a local variable in the arrayList method. Instead of this:
    Java Code:
    ArrayList<String> al = new ArrayList<String>();
    in the method, use this
    Java Code:
    static ArrayList<String> al = new ArrayList<String>();
    at the beginning of the file, and take the line out of the method.

    Next, change your for loop code to use if(al.get(i).contains(input)) (contains returns true if the string contains the specified substring, false otherwise, so the conditional code will execute only if al.get(i) contains the given input) and print the string if it does contain it.

    You really need to find a good book explaining parameters, local variables, methods, member variables, and static variables, and scope. I can't recommend any as I am self-taught off web tutorials, but I'm sure some members of the forum know of some
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  17. #17
    spleenlol is offline Member
    Join Date
    Feb 2010
    Posts
    11
    Rep Power
    0

    Default

    thanks so much! i got it working. here is the final code:
    Java Code:
       static ArrayList<String> al = new ArrayList<String>();
        public static void arrayList(String txtIn)
        {
            Scanner in = new Scanner(System.in);
            System.out.print("Enter a string of text: ");
            String input = in.nextLine();
    
           
            al.add(input);
             Scanner in2 = new Scanner(System.in);
            System.out.print("Would you like to enter more text? Please answer Y or N: ");
            String input2 = in2.nextLine();
          
            if (input2.equals("Y") || input2.equals("y"))
            {
                arrayList(txtIn);
            }
            else if (input2.equals("N") || input2.equals("n"))
            {
                Scanner in3 = new Scanner(System.in);
                System.out.print("Enter a substring to search: ");
                String input3 = in3.nextLine();
                for (int i=0;i<al.size();i++)
                     {
                        al.get(i).contains(input3);
                        if (al.get(i).contains(input3))
                        {
    
                            System.out.println(al.get(i));
                        }
                     }
                beginning(null);
            }
            else
            {
                System.out.println("You didn't enter Y or N.");
            }
    
        }
        public static void addStringArray(String txtIn)
        {
            System.out.print("Would you like to add strings to an array? Y or N: ");
            Scanner in = new Scanner(System.in);
            String input = in.nextLine();
            
            if (input.equals("Y") || input.equals("y"))
            {
                arrayList(txtIn);
            }
            else if (input.equals("N") || input.equals("n"))
            {
                System.out.println("Okay see you!");
            }
            else
            {
                System.out.println("You didn't enter Y or N.");
                addStringArray(txtIn);
            }
        }
        
        public static void main(String[] args) 
        {
          
            addStringArray(null);
        }
    I have it after you search it goes to the other code I already had. If you can recommend a good book let me know please! Thanks again and sorry for all of the trouble. >.<

  18. #18
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Well, just about any book that teaches OOP (Object-Oriented Programming) concepts should help get you started - I'll tell you now that in Java static variables are very similar to global variables, but they have a visibility setting (public, private, protected, and the so-called "package private" that you should never use - you did, but it doesn't matter too much in a program this small, though you could make al private)

    The Sun Java Tutorials are very useful, specifically, in your case Learning the Java Language. It explains OOP concepts as well as teaching you some of the quirks of java that other languages don't have. (package private, packages in the first place (except python, which is a stupid language really), and the lack of global variables, which most languages have as compatibilty for older versions.) You probably know some of it, but give it a good read, as it should refresh and ingrain it in your memory, as well as giving you information on scope and other things.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  19. #19
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Singing Boyo View Post
    The OP's method signature:

    Java Code:
        public static void searchArray(String txtIn)
        {
            //add code to search for text
            
        }
    your code:
    Java Code:
    boolean isSubstring(List<String> list, int i, String str) {
       return list.get(i).indexOf(str) >= 0;
    }
    You added two parameters, which reasonably should be there, but his method didn't have them. And it looks even more like C code than his does. If he tried to put that it and had it called from a different class, something would break...

    And it may not be quite a full-blown solution, but it's definitely close.
    True, I gave away the actual clue of the problem and supplied a small method that can do part of the trick; I suspected the OP to fit in my little method in his/her program; I wasn't spoonfeeding and there is absolutely no rule that states that different methods should have identical signatures.

    kind regards,

    Jos

Similar Threads

  1. Binary search tree search method
    By chopo1980 in forum New To Java
    Replies: 2
    Last Post: 12-10-2009, 02:42 AM
  2. Replies: 0
    Last Post: 10-29-2009, 10:28 AM
  3. Search function for ArrayList?
    By javanoobie in forum New To Java
    Replies: 11
    Last Post: 04-17-2009, 09:38 PM
  4. Replies: 5
    Last Post: 08-26-2008, 04:43 PM
  5. Replies: 2
    Last Post: 04-21-2008, 12:43 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •