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) + " |");
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.