0

I have used TreeMaps to calculate the frequencies of letters in user-entered text. When displaying these frequencies I get quite a messy output as some frequencies are zero, and others are numbers to one or two decimal places.

An example, from entering Harry:

Letter |a |b |c |d |e |f |g |h |i |j |k |l |m |n |o |p |q |r |s |t |u |v |w |x |y |z |
Count  |0.2 |0 |0 |0 |0 |0 |0 |0.2 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0.4 |0 |0 |0 |0 |0 |0 |0.2 |0 |

How do I produce a table which is neatly spaced (and without knowing the frequencies), like this:

Letter |a   |b |c |d |e |f |g |h   |i |j |k |l |m |n |o |p |q |r   |s |t |u |v |w |x |y   |z |
Count  |0.2 |0 |0 |0 |0 |0 |0 |0.2 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0.4 |0 |0 |0 |0 |0 |0 |0.2 |0 |

To produce my table I have used simple for loops which increment through the Treemap, and I was thinking of the System.out.format command, but I'm still learning a lot about java so this would probably be wrong.

My for loops are here:

System.out.print("Letter |");
for (char a: Allmap.keySet()) {
  System.out.print(a + " |");
}

System.out.print("\n" + "Count  |");
for (double b: Allmap.values()) {
  System.out.print(df.format(b / CHARCOUNT) + " |");
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Harry Jones
  • 73
  • 2
  • 3
  • 11
  • If you don't mind that, printing all the numbers with the same number of digits is the simplest way to do it (0.00, 0.20, 0.37, etc.). Otherwise you should check, before printing the letter, the number of digits used by the number. – Diego Martinoia Mar 24 '15 at 11:51
  • 1
    Related: http://stackoverflow.com/q/2745206/3182664 (also see the "Linked" answers/questions), and I recently created a utility class for that http://stackoverflow.com/a/29054406/3182664 – Marco13 Mar 24 '15 at 11:55
  • @Marco13 Thank you for the helpful links. May I ask why you downvoted the question? – Harry Jones Mar 24 '15 at 14:33
  • @HarryJones I did not vote. (I rarely vote at all) – Marco13 Mar 24 '15 at 17:22

1 Answers1

1

I assume you want something like this, although I haven't had time to test it.

System.out.print("Letter |");
for (char a : Allmap.keySet()) {
    System.out.print(a + " |");
}

System.out.print("\nCount  |");
for (double b : Allmap.values()) {
    System.out.printf( "%.2f |", d );
}

Also note that this code will round the double to two decimal places, so 3.14159 becomes 3.14, and 2.71828 becomes 2.72.

Also, here was my source for rounding a double to two decimal places: Round a double to 2 decimal places

Community
  • 1
  • 1
mgthomas99
  • 5,402
  • 3
  • 19
  • 21