2015-05-17 60 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);

相关问题