2015-05-17 62 views
1

我對Java很新。我一直在研究如何在數組中找到最常見的字符串,並且我的代碼沒有按照它的工作方式工作。我的錯誤是mostCommon打印出null當我需要它打印出最頻繁的IP地址。查找ArrayList中最常見的字符串 - 當前返回null

這是我的代碼...

public class Log_File_Analysis 
{ 

private static ArrayList<String> ipAddress = new ArrayList<>(); 
private static String temp , mostCommon; 
int max = 0, num = 0; 


public String getMostUsedIpAddress() 
{ 
    Collections.sort(ipAddress); 
    for (String string : ipAddress) 
    { 
     if (string.equals(temp)) 
     { 
     num++; 
     } 
     else { 
     if (num>max) 
     { 
      max = num; 
      mostCommon = string; 
     } 
     num = 1; 
     temp = string; 
     } 
    } 
    return mostCommon; 
} 

public static void main (String[] args) 
{ 
    System.out.println("Enter a log file to be analyized"); 
    //Scanner keyboard = new Scanner(System.in); 

    File filename = new File("small.log");    
    try 
    { 
     Scanner data_store = new Scanner (filename); 
     while(data_store.hasNext()) 
     { 
      String line = data_store.nextLine(); 
      int begin = line.indexOf("[client ") + 8; 
       int end = line.indexOf("]", begin); 
      String ip = line.substring(begin, end); 
      ipAddress.add(ip); 
      System.out.println(ip); 
     } 
     data_store.close(); 
    } 
    catch(FileNotFoundException e) 
    { 
     System.out.println("small.log was not found!");   
    } 
    System.out.println(mostCommon); 
} 

} 

能否請你幫我明白我做錯了。

+0

它看起來並不像'getMostUsedIpAddress'被稱爲有史以來 – Andbdrew

+0

你也應該讓'static',如果你想從叫它'main' – Andbdrew

+0

@Andbdrew謝謝 – Sammie

回答

1

你的代碼中沒有任何地方是你實際調用你的方法來確定最常見的值。

您需要添加到您的main()方法結束...

mostCommon = getMostUsedIpAddress(); 
System.out.println(mostCommon); 

基本上,你讀完所有的值,所以現在你需要打電話給你的方法來找到最共同的價值,那麼你可以顯示它。目前,您的代碼正在打印null,因爲您實際上並未嘗試在任何地方設置mostCommon的值。

+0

這是不行的,因爲'getMostUsedIpAddress'是實例方法 – Andbdrew

+0

@WATTO Studios謝謝!我不知道我錯過了那個笑聲:) – Sammie

0

你似乎沒有調用你的getMostUsedIpAddress方法。

嘗試更改 System.out.println(mostCommon); 至 System.out.println(getMostUsedIpAddress());

由於您正在返回mostCommon而不是將其設置爲變量。

0

您沒有初始化兩個字符串temp和mostCommon。 可能是主要問題! 它們通常被初始化爲String temp =「」;如果他們沒有內容(就像初始化一個int值爲0);

相關問題