计算'x'字母单词的数量

时间:2014-03-03 20:03:25

标签: java string

我现在有了这段代码,如果我输入“你好吗”这个词,它会输出'3 3 3'然而我想编辑我的代码,以便它输出有3'3'字母的单词,我该怎么做?

 import java.util.*;

    public final class CountLetters {

      public static void main (String[] args) {

        Scanner sc = new Scanner(System.in);

        String words = sc.nextLine();

        String[] letters = words.split(" ");

        for (String str1 : letters) 

        {
        System.out.println(str1.length() ); 
        }


      }

    }

2 个答案:

答案 0 :(得分:1)

添加int的数组以跟踪每个字长的计数。

对于每个单词,增加数组中与单词长度对应的值。

最后,浏览你的int数组并打印出每个长度的单词数。对于此步骤,您应该添加一个条件,以便仅在计数为>时才打印。 0

答案 1 :(得分:0)

您可以使用HashMap。

public static void main(String[]args){

  Scanner input = new Scanner(System.in);
  String bubba = input.nextLine();



  Map<Integer,Integer> occurrences = new HashMap<Integer,Integer>(); 

  for(String currentWord: bubba.split(" ")){
      Integer current = occurrences.get(currentWord.length());
      if(current==null){
          current = 0;
      }

      occurrences.put(currentWord.length(), current+1);
  }

  for(Integer currentKey: occurrences.keySet()){
      System.out.println("There are "+occurrences.get(currentKey)+" "+currentKey+" letter words");
  }

}
相关问题