我对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);
}
}
能否请你帮我明白我做错了。
它看起来并不像'getMostUsedIpAddress'被称为有史以来 – Andbdrew
你也应该让'static',如果你想从叫它'main' – Andbdrew
@Andbdrew谢谢 – Sammie