2014-03-03 73 views
0

我現在有了這段代碼,例如,如果我輸入'你好嗎',它會輸出'3 3 3',但是我想編輯我的代碼,以便輸出有3'3'字母的單詞,我該怎麼做?計數'x'字母的數字

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()); 
     } 


     } 

    } 

回答

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"); 
    } 

} 
+0

謝謝,這是有道理的 – user3376304

1

添加一個數組int s來跟蹤每個字長的計數。

對於每個單詞,增加數組中對應於單詞長度的值。

最後,遍歷你的int數組,並打印出每個長度有多少個單詞。對於這一步,您應該添加一個條件,以便只在計數> 0時打印。

+1

如果您知道輸入中最長的字長,那麼就是您的數組大小。如果不是,您可以通讀輸入兩次,一次確定最長的單詞,然後第二次計算所有長度。第三種選擇是使用地圖,其中關鍵字是字長,值是長的字數。 –