I have been asked to produce a program which reads a file and writes it all to an ArrayList, furthermore I must print this out which I have been able to do.
The next part I am asked to perform a search in the ArrayList which asks the user what word they would like to search for and then the program will find this word in the ArrayList and prints the whole string line it occurs on, whilst tallying how many times it occurs. So far my program looks like this:
As you can see I am as far as prompting a user for the word input and iterating the book, although I'm clueless as to how I can search through the ArrayList to print the line that the word occurs on and how to count how many times it comes up.. Can anyone give me a push in the right direction?
Well, you're already iterating through your ArrayList to print it out. So you need to modify that so that for each line you check to see if userInput appears in the line, and only prints it out if it does.
Look at the Javadocs for the String class, and you should find a method that will help you peform this check.
Nitin Surana wrote:you can use something like this
Please don't do the OP's work for him. This site is NotACodeMill, and, as it states right at the top of the Beginning Java topics list page: "We're all here to learn, so when responding to others, please focus on helping them discover their own solutions, instead of simply providing answers."
Joanne Neal wrote:What if the line contains the word 'accountable' and the user was looking for 'count'. Should that line be included ?
Should the search be case sensitive or not ?
And how should it affect the count if the string appears multiple times on the same line?
If this is an introductory exercise, I suspect the easier option of these questions was intended, but I may be wrong.
Joined: Aug 05, 2005
Matthew Brown wrote:If this is an introductory exercise, I suspect the easier option of these questions was intended, but I may be wrong.
I agree. But it's always good to get beginners thinking about what they are doing and anticipating any potential problems.
Joined: Jan 13, 2012
Thanks for the warm welcome Matthew.
Yeah sorry for the stir! Was just asking for a push in the right direction as I have not really touched on searching yet. Thanks for all the input so far guys, it is much appreciated. Yeah, I need to take into account words that may be within words and not count them for example, like what Joanne has stated. Just counting the specific times the word input by the user actually comes up.
I'm going to enter an .equalsIgnoreCase later on, just getting the fundamentals down.
Nitin Surana wrote:here is how you can count the occurrences.
Once again: Please don't do the OP's work for him. This site is NotACodeMill, and, as it states right at the top of the Beginning Java topics list page: "We're all here to learn, so when responding to others, please focus on helping them discover their own solutions, instead of simply providing answers."