如何更改&#34的输出;我的名字是"从{2 = 1 4 = 1}到>长度为2的单词数为1,然后在下一行中,长度为4的单词数量为1,就像下面的输出一样:
//You have typed the sentence: my name is
//the number of words with the length of 2 is 1
//the amount of word with the length of 4 is 1
基本上如何更改' {2 = 2,4 = 1}'一句话?
这是我的代码:
public static void main(String args[]) {
System.out.println("Write your sentence please:");// prints out the first instruction.
Scanner scan = new Scanner(System.in); //object initialisation.
String line=" ";//declaration for letters(String) characters.
//int max = 20; //declaration for number(int) characters.
while((line=scan.nextLine())!=null) { //scanner instruction, get a line from the key board.
String[] tokens = line.split(" ");// splits the words
Map<Integer,Integer> tokensLength = new HashMap<Integer,Integer>();
for (int i = 0; i < tokens.length; i++) {// this line of code checks for what must be true to carry on.
int length = tokens[i].length();
if (tokensLength.containsKey(length))
tokensLength.put(length, tokensLength.get(length) + 1);
else
tokensLength.put(length, 1);
}
for (Integer length : new TreeSet<Integer>(tokensLength.keySet()))
System.out.println("You have typed the sentence: " + line);//prints out what you have typed.
System.out.println("The word length frequency of the sentence is " + tokensLength);//prints out the results
}//End of scanner instruction
}//End of main
谢谢!任何帮助将非常感激!
答案 0 :(得分:0)
使用它迭代地图并编写好的句子:)
for (Entry<Integer, Integer> entry : tokensLength.entrySet()){
System.out.println("There are "+entry.getValue()+" words of length "+entry.getKey());
}