Java 如何将输出更改为字数?
如何将输出从{2=1 4=1}更改为>长度为2的字数为1,然后在下一行中,长度为4的字数为1,如下所示:Java 如何将输出更改为字数?,java,output,Java,Output,如何将输出从{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 st
//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
谢谢大家!!任何帮助都将不胜感激 用它在地图上迭代并写出漂亮的句子:
for (Entry<Integer, Integer> entry : tokensLength.entrySet()){
System.out.println("There are "+entry.getValue()+" words of length "+entry.getKey());
}
欢迎来到堆栈溢出。你有没有试过什么特别的东西?你在哪里卡住了?这是一个家庭作业问题吗?目前“我的名字是”的输出是句子的字长频率是{2=2,4=1}。我如何将输出稍微更改为上面描述的输出形式?基本上,我如何将{2=2,4=1}更改为句子形式?