Can you tell me how elegant this solution is for the problem? I tried using as little code as required. This is basically listing how many times a word appears in a line of text. I have converted the text to a string array.
I'll let someone more experienced comment on elegance, but I wanted to point out that your code fails to identify words that are adjacent to punctuation marks. The presence of a period, comma or question mark next to a word will give you faulty results.
Ryan Sykes wrote:I'll let someone more experienced comment on elegance, but I wanted to point out that your code fails to identify words that are adjacent to punctuation marks. The presence of a period, comma or question mark next to a word will give you faulty results.
I've fixed that issue. However, if somebody enters a word that has punctuation in the middle of the word, such as 'it's' or 'jack-in-the-box' it will make these words 'its' and 'jackinthebox'
Both examples are very poor because they have too long a main method. Ideal length of main method: one statement.
Use of static members appears inappropriate.
Why are you using an array to store the Strings? There are far more appropriate data structures.
Failure to close readers. Failure to handle exceptions locally.
You're also looping through the array far more than is necessary. You've got a main loop, but inside that you keep looping up to the current point to find out if you've found the word yet, then loop from that point onwards to count them.
My first thought would be to use a HashMap, containing words mapped against the number of times they occur. Then you only have to loop through the array once - check if the word is in the map (a very fast operation - HashMaps are designed to be good at that), add it if not, and increment the count if it is. Then loop once through the map to print the values.
The main method is intended for starting your application. You can often do that with a class you instantiate and call one method onOne line. I know people will disagree with me on that.
You want a class which runs your application, and you want objects which you manipulate. You are nowhere creating an object which runs your application. In the case of a little application like that, you can get away with few objects; a larger application will require many objects to run it.
A magnificient life is loaded with tough challenges. En garde tiny ad:
a bit of art, as a gift, the permaculture playing cards