0


I made a program that counts the number of occurrences of all the letters in a given String using TreeMap(String, Integer) (named alphaFreq). Now I want to represent these occurrences as percentages ([A=12.3] , [B=3.0] , ....etc), so I created another TreeMap (String, Double) (named percentage), copied all keys with their values set to zero, and edited the value according to that in alphaFreq as follows:

for(int i=0; i<26; i++){
   int temp;
   Character current = (char)(i+65);
   String frog = current.toString();
   temp = alphaFreq.get(frog);
   int perc = (temp/cipherLetters.length)*100;
   System.out.println(temp+"/"+cipherLetters.length+" = "+perc);
   percentage.put(frog,(double)perc);
}

If the String is all As or Bs, the result is all keys have a value of zero except A=100.0 or B=100.0 But if the String text has any other combination (say: DDJJSHHIEM) they all have the value of zero. Why? What am I doing wrong?................Thanks

Aelgawad
  • 184
  • 1
  • 16

1 Answers1

2

First thing I would do is change your calculation of percentage to:

int perc = (temp * 100)/cipherLetters.length;

Given that you are using integer division, (temp/cipherLetters.length) is probably zero.

Vishal K
  • 12,976
  • 2
  • 27
  • 38
jarmod
  • 71,565
  • 16
  • 115
  • 122
  • 1
    You are welcome. Be sure to click the check mark for correct answers so that others know the problem has been resolved. Also, if you need your percentage to be more accurate (such as 63.5% rather than rounded to 63% as it is right now) then you'll need to use float rather than int. – jarmod May 04 '13 at 17:28
  • I made it double once and float once but it yields 16.0 or 63.0 when it should be 16.667 or 63.533, Any Thoughts? – Aelgawad May 04 '13 at 20:39
  • You'll have to do more than simply change 'int perc' to 'float perc'. The right-hand side of your assignment is still using integer arithmetic so is rounding. Try 'float perc = ((float)temp * 100.0f) / (float)cipherLetters.length;' – jarmod May 04 '13 at 22:18
  • Uhaaah looks like I need a lesson at that stuff. One final question. Is there a way that I can round it up to one decimal place (12.4) instead of 6 decimal places? – Aelgawad May 05 '13 at 10:36
  • See http://stackoverflow.com/questions/11701399/round-up-to-2-decimal-places-in-java – jarmod May 06 '13 at 12:56