2016-02-21 44 views
-3

所以,我需要編寫一個代碼,在其中打印數組中最頻繁的字符。如果有,那麼只有一個打印該字符,如果有兩個然後打印兩個字符,並且如果沒有則打印沒有數字丟失。我已經找到了最頻繁的單個值,但如果有多個頻繁字符,我無法弄清楚如何進行打印。如何查找數組中最頻繁的字符?

public class ArrayOfNumbers { 
    public static void main (String []args) { 
    int [] array = {2,3,5,1,2,3}; 
    int n = 6; 
    System.out.println(findMostFrequent); 
} 
    public static int findMostFrequent(n, array) { 
    int counter = 1; 
    int tempCounter; 
    int mostFrequent = array{0}; 
    int temp = 0; 
    for (int i = 0; i < array.length - 1; i++){ 
     temp = a{1}; 
     tempCounter = 0; 
     for (int j = 1; j < array.length; j++){ 
      if (temp == a[j]){ 
       tempCount++ 
      } 
      if (tempCounter > counter){ 
       mostFrequent = temp; 
       counter = tempCounter; 
      } 
     } 
     return mostFrequent; 
    } 
    } 
} 
+1

此代碼甚至不編譯 - 多個錯誤。請修正編譯錯誤,然後描述當前的行爲。 – pczeus

+2

http://stackoverflow.com/questions/8545590/java-find-the-most-popular-element-in-int-array的副本 –

回答

1

你的代碼有很多錯誤!

  • 獲取陣列中第n項不符合a{1}a[0]
  • 解析這個值int,而不是int[](這是一個單值)
  • 這調用是錯誤的System.out.println(findMostFrequent);。有參數丟失
  • 變量tempCount尚未在findMostFrequent方法中初始化。
  • 根本不需要長度變量int n。你得到的數組大小爲array.length

  • 壞拷貝從Java - Find the most popular element in int[] array

相關問題