2016-11-10 916 views
0

我想計算Java數組中每個數的出現次數(如1 =?,2 =?,3 =?)。我的數組如何存儲超過10個值?計算數組java中的出現次數

int [] arryNum = new int[]{4,4,4,3,4,5,4,3,4,4,4,5,4,5,5,5,4,3,2,15,4,3,4,6,4,3,4,5,4,2,4,5,4,3,2,5,4,3,5,4,0,4,3,4,5,4,3,0,4,5,4,3,5,4,2,3,2,3,4}; 
    int[] counter = new int[] { 0, 0, 0, 0, 0,0 }; 
    for (int i = 0; i < arryNum.length; i++) { 
     counter[arryNum[i] ]++; 
    } 

    for (int i = 0; i < counter.length; i++){ 
     System.out.println((i + 1) + ":" + counter[i]); 
    } 
+0

使用「Map 」鍵,其中鍵爲數字,值爲頻率/計數器。 – Thomas

+0

erm ... sry @Thomas我在java中很新,我可以知道如何根據我的問題使用Map 來存儲我的值嗎? –

+0

查看[Map Interface](https://docs.oracle.com/javase/7/docs/api/java/util/Map.html)。 Map本身就是一個接口,所以你不能直接創建它的一個實例,但是你可以創建一個子類的實例; IE:Map map = new HashMap ();'。從那裏,你可以使用'put(K,V)','get(K)'和'containsKey(K)'方法去做你想做的事情。 – Ironcache

回答

1
public static void main(String[] args){ 
    int[] arryNum = new int[] { 4, 4, 4, 3, 4, 5, 4, 3, 4, 4, 4, 5, 4, 5, 5, 5, 4, 3, 2, 15, 4, 
      3, 4, 6, 4, 3, 4, 5, 4, 2, 4, 5, 4, 3, 2, 5, 4, 3, 5, 4, 0, 4, 3, 4, 5, 4, 3, 0, 4, 
      5, 4, 3, 5, 4, 2, 3, 2, 3, 4 }; 
    Map<Integer, Integer> lookup = new HashMap<>(); 
    for (int key : arryNum) { 
     if(lookup.containsKey(key)) { 
      lookup.put(key, lookup.get(key) + 1); 
     } else { 
      lookup.put(key, 1); 
     } 
    } 

    for (Integer keys : lookup.keySet()) { 
     System.out.println(keys + " Found " + lookup.get(keys) + " Times"); 
    } 

} 
+0

我實際上是想貶低你的答案,因爲你沒有一個單一的解釋線......但是。每個人都開始......但請記住:**好**的答案不僅僅是放棄一些工作代碼! – GhostCat

1

你可以不喜歡這樣。

首先你需要的地圖來算你的東西:

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

然後你遍歷你的號碼;最好用的for-each:

for (int number : arryNum) { 
    if (countsByNumbers.containsKey(number)) { 
    int newCount = countsByNumbers.get(number) +1; 
    countsByNumbers.put(number, newCount); 
    } else { 
    countsByNumbers.put(number, 1); 
    } 

一些注意事項:

  1. 要知道,地圖,因爲任何類型的Java集合類的只有參考類型的交易;因此它被聲明爲使用Integer,而不是原始類型int
  2. 編譯器做了一些魔法把從你的陣列INT值到整數對象的掩護下
  3. 注意Map是一個接口,但我們必須實例化一個具體的類,在此情況下,我們簡單地使用的HashMap
+0

好的解決方案,但是你應該使用containsKey(),contains()對於Map不存在。 – user6904265

+0

謝謝......修正了它! – GhostCat

1

您可以將其與Java 8流寫在一個更succint方式:

Map<Integer,Integer> map = new HashMap<Integer,Integer>(); 
Arrays.stream(arryNum).forEach(x -> map.put(x , map.computeIfAbsent(x, s -> 0) + 1)); 
System.out.println(map); 
+0

提示:對於初學者...流很可能矯枉過正。 – GhostCat

+0

是的,對於初學者來說,你的解決方案更合適。 – user6904265