2016-03-01 727 views
-2

我正在編寫一個程序,其中我使用數字0到20中的隨機整數元素生成100個整數元素的數組。我被告知要編寫一個方法來計算多少次生成每個值0到20。我試圖寫這部分代碼,但沒有任何工作。有人能幫我解決我在做什麼錯嗎?這是我一直在努力的代碼。Java:計算數組中每個元素的出現次數

public static void arrayCounter() 
{ 
    int[] counter = new int[21]; 
    for (int x = 0; x < counter.length; x++) 
    {    
     for (int i = 0; i < randomArray.length; i++) 
     {  
      if (i == randomArray[x]) 
      counter[x]++;  
     } 
     System.out.println("Element " + x + " : " + counter[x] + " times"); 
    } 
} 
+0

想象一下某個未知的人來顯示,向您展示一些代碼並說*「沒有任何工作」*。你會怎麼想?你會認爲「啊,我明白她期望得到什麼,她現在得到什麼以及爲什麼這是錯的」,或者你會認爲「可以請你解釋一下你的問題」嗎? – Tom

回答

1

你在想這個,你不需要嵌套循環來訪問數組中的每個元素,你只需要一個索引。

public static int[] count(int[] array, int maxValue) { 
    int[] count = new int[maxValue + 1]; 
    // for each value. 
    for (int n : array) count[n]++; // increment the counter for that value. 
    return count; 
} 

您可以

Random rand = new Random(); 
int[] array = new int[100]; 
for (int i = 0; i < array.length; i++) array[i] = rand.nextInt(21); 

int[] count = count(array, 20); 
for (int i = 0; i < count.length; i++) 
    System.out.println(i + ": " + count[i]); 

運行在這裏http://ideone.com/utSNd3打印

0: 5 
1: 5 
2: 4 
3: 6 
4: 4 
5: 9 
6: 5 
7: 9 
8: 1 
9: 3 
10: 4 
11: 11 
12: 2 
13: 6 
14: 1 
15: 6 
16: 5 
17: 3 
18: 4 
19: 4 
20: 3 
+0

當我在我的代碼中嘗試這個時,我的程序將無法加載。我怎樣才能打印這個? – Alyssa

+0

@Alyssa我已經添加了一個如何調用它並打印結果的例子。 –

+0

@Alyssa對你的個人資料發表評論;隨着你學習的越多,你會意識到遠比一個人所能學習的東西還要多。當你不知道所有事情時,你都會學習如何工作。 –

0

嘗試創建一個變量int count這樣調用這個:

int count =0; 
for (int x = 0; x < counter.length; x++) 
    {    
    for (int i = 0; i < randomArray.length; i++) 
    {  
     if (randomArray[i] == randomArray[x]) 
     count++;  
     } 
    } 

    System.out.println("Element " + x + " : " + count + " times"); 
+0

你不需要嵌套循環。 –

1

ÿ OU應該

if (x == randomArray[i]) 

嘗試,而不是

if (i == randomArray[x]) 

另一個解決方法: 停止使用數組。 你可以使用流,如果你有Java的8或收藏與Java 6+這應該工作:

Set<T> mySet = new HashSet<T>(Arrays.asList(someArray)); 
int occurrences = Collections.frequency(mySet, x); 

只需添加一個循環測試X

0

的每個值另一個更動態的解決方案可能是使用一個Map來識別出現值的頻率。它基本上與@PeterLawray使用的原理相同,但不是使用帶有定義值的索引的array,而您需要首先知道數組的最大值,此解決方案確實使用mapkey來標識每個值。

public static void main(String[] args) { 
    int[] testArray = {0, 1, 1, 3, 4, 15, 1, 2, 3, 5}; 
    count(testArray); 
} 

public static void count(int[] array) { 
    Map<Integer, Integer> counter = new HashMap<Integer, Integer>(); 
    for(int i : array) { 
     // If the value was already found, increase it´s occurence, 
     // otherwise the value occured once yet, so we put 1 in there 
     counter.put(i, counter.get(i) == null ? 1 : counter.get(i) + 1); 
    } 
    for(Entry<Integer, Integer> entry : counter.entrySet()) { 
     System.out.println("The value " + entry.getKey() + " appears " + entry.getValue() + " times"); 
    } 
} 
相關問題