我正在完成一项教学任务,教我们一些关于地图的知识 到目前为止我有这个代码
import java.util.Map;
import java.util.TreeMap;
import java.util.Scanner;
import static java.lang.System.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Histogram
{
private Map<String,Integer> histogram;
public Histogram(String sent)
{
histogram = new TreeMap<String,Integer>();
String[] words = sent.split(" ");
for(String c : words)
{
if(histogram.containsKey(c))
{
histogram.put(c,histogram.get(c)+1);
}
else
{
histogram.put(c,1);
}
}
}
public String toString()
{
String output="";
output+="char\t1---5----01---5\n";
String z ="";
for(String s: histogram.keySet())
{
for(int x=0 ; histogram.size() > x;x--)
{
z += "*";
}
}
return output+ "\n\n" ;
}
}
我希望这样的字符串格式化
char 1---5----01---5
a **
b *
c **
d **
e **
f *
g **
h ***
i **
k *
我正确分配了星号,我将如何格式化它显示键然后是#of *'s
如果需要,这是另一部分
public class HistogramTester
{
public static void main( String args[] ) throws IOException
{
Scanner in = new Scanner(new File("Histogram.dat"));
while (in.hasNextLine())
{
String n = in.nextLine();
Histogram a = new Histogram(n);
System.out.println (a);
}
}
}
如果有帮助,这里是dat文件
a b c d e f g h i a c d e g h i h k
1 2 3 4 5 6 1 2 3 4 5 1 3 1 2 3 4
Y U I O Q W E R T Y
4 T # @ ^ # # #
答案 0 :(得分:0)
试试这个:
for(String s: histogram.keySet()) {
StringBuilder str = new StringBuilder();
Integer value = histogram.get(s);
if (value!=null)
for(int x = 0; x < value.intValue(); x++) {
str.append("*");
}
output+=s+"\t"+str.toString()+"\n";
}