我對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