2016-03-24 52 views
-1

我想創建一個名爲printFrequency的方法,將我的每個可能值(0,1,...,9)出現的總次數相加並打印出來碼。我想在java中使用printFrequency方法

import java.util.Random; 

public class Array { 

    int[] array; 
    int size = 0; 

    public Array(int s) { 
     size = s; 
     array = new int[size]; 
    } 

    public void print() { 
     for (int i = 0; i < size; i++) 
      System.out.printf("%d,", array[i]); 
     System.out.println(); 
    } 

    public void fill() { 
     Random rand = new Random(); 
     for (int i = 0; i < size; i++) 
      array[i] = rand.nextInt(10); 

    } 

    public void sort() { 
     for (int i = 0; i < size; i++) { 
      int tmp = array[i]; 
      int j = i; 

      for (; j > 0 && (tmp < array[j - 1]); j--) 
       array[j] = array[j - 1]; 
      array[j] = tmp; 
     } 
    } 

    public void printFrequency() { 

    } 
} 

我想爲printFrequency方法的輸出是這樣的:

Frequencies: 
There are 2, 0's 
There are 0, 1's 
There are 0, 2's 
There are 0, 3's 
There are 3, 4's 
There are 0, 5's 
There are 2, 6's 
There are 1, 7's 
There are 0, 8's 
There are 2, 9's 

我不知道如何開始使用它,並使用什麼環路,或是否有更簡單的方法來做到這一點

+0

不要將您的班級命名爲'Array'。使用API​​中現有的類名會降低可讀性,並且在您實際導入「Array」類時可能會產生問題。 – Ram

回答

0

我想創建一個方法叫做printFrequency該加起來,並打印,每個可能的值的出現的總數目(0,1,...,9)

假設要計算在array本號的頻率,這裏是使用固定長度的數組充當通過計數0桶的每個號碼中的一個溶液 - 9.

這裏是代碼片斷:

private static void printFrequency() { 
    int[] countArray = new int[10]; 
    for(int x : array) { 
     countArray[x]++; 
    } 

    System.out.print("Frequencies: "); 
    for(int i = 0; i < 10; i++) { 
     System.out.print("There are " + countArray[i] + ", " + i + "'s "); 
    } 
}