• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calculating percentages from a map iteration  RSS feed

 
Jack Fletcher
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stuck trying to understand why this piece of code doesn't work.
I am trying to iterate through each associated key and value in a map and print out the value as a percentage.
The aim of the program is to count the occurence of each character in a read text file, everything but this piece of code works fine so far.

'countAllCharacters' is a global variable, when made local it behaves exactly the same.

 
Bin Smith
Ranch Hand
Posts: 514
1
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

If entry.getValue() is current number of occurrence of certain character then it should not work.
Because you do not know total number of occurrences of that character. So, if countAllCharacters is total number of occurrences
of searched character then it cannot be determined untill you find all characters. Otherwise you cannot calculate percentage.

 
Jack Fletcher
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi sorry I should have included the other piece of code which increments the count as each letter is read into the map:

 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int division in Java is different than how we do it mathematically. Remember, the decimal part is discarded.
 
Bin Smith
Ranch Hand
Posts: 514
1
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot calculate percentage of occurrence of character without having total number of occurrences of this same character.
I see that you calculate percentage of occurrence of one character by using total number of all characters countAllCharacters. This is wrong.
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A 2/50 is 0, not 0.04.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jack Fletcher wrote: . . . 'countAllCharacters' is a global variable, . . .
Never use global variables. The design of classes is intended to prevent them. It might work here, but global variables are notoriously error‑prone. If you mean it is a private field in your current class, that is different. That is not a global variable, and that sort of thing is all right.

You need to revise your integer arithmetic. What do you get if you work out i / j if i > 0 && j > 0 && j > i? I presume you never count enough to get an overflow error.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!