• Post Reply Bookmark Topic Watch Topic
  • New Topic

Counting certain words in an txt file  RSS feed

 
Donogh Keane
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am having a problem with the attached code. It is giving an error at "if (parts=='banana')". Any help would be much appreciated

What I am trying to do:

First create a Set of 5 allowed fruit names.
A valid file contains fruit names that are separated by whitespace, e.g. a space, a tab or a
newline.
Each fruit name can be present more than once in the file.
Read the file and every time the name of a fruit is encountered, if that fruit is in the set of
allowed fruit names, increment a total in a Map using the fruit name as the key, and the
counter as the value.
Once the file has been read and closed, and the map fully updated, write each key/value pair
in the map to the console.
Example input file:
banana apple pear banana peach pineapple apple pear peach pear
Example console output (if all the fruit in the input file are in the allowed Set):
banana: 2
apple: 2
pear: 3
pineapple: 1
peach: 2


My code:

4.JPG
[Thumbnail for 4.JPG]
 
Campbell Ritchie
Marshal
Posts: 56595
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for delay in replying.
I can see two things you are doing wrong. String literals don't use 'single quotes' but "double quotes".
You shouldn't use == operator on reference types like that.

There is a totally different approach with a Map, which may be too advanced for you: look in the Java™ Tutorials.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!