所以我完全停留在我的java类的作业分配上。其中,我需要编写一个程序来分析Web服务器的日志文件,以确定哪台计算机试图访问该Web服务器的最多。我选择使用地图来跟踪与之一起运行的文件,以便每次使用整数值保存每个唯一地址,每次代码找到重复的IP地址时都会增加该值。在HashMap中增加单个值
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class LogTester
{
public static void main(String[] args)
{
int individualCounter = 0;
int ipcounter = 0;
Map<String, Integer> ipCheck = new HashMap<String, Integer>();
System.out.println("Enter a log file to be analyzed");
Scanner ui = new Scanner(System.in);
String filename = ui.nextLine();
File name = new File(filename);
try
{
Scanner dataStore = new Scanner(name);
while(dataStore.hasNextLine())
{
//get the entire line from the log file
String line = dataStore.nextLine();
//find the location of the word "client", then move 7 more spaces (see log file)
int subscriptOfClient = line.indexOf("client");
String s1 = line.substring(subscriptOfClient + 7);
//we now have a smaller string
//this string begins with the IP address
//se we find the ending bracket and extra the ip
int subscriptOfBracket = s1.indexOf("]");
String s2 = s1.substring(0, subscriptOfBracket);
ipcounter++;
ipCheck.put(s2, individualCounter++);
//print out the IP(in the assignment, put this into a map)
}
System.out.println("Found " + ipcounter + " unique IP addresses.");
System.out.println("The most suspicious are: ");
for(String key : ipCheck.keySet()){
System.out.println(key);
}
}
catch (FileNotFoundException e)
{
System.out.println("Could not open that file");
}
}
}
我现在面临的问题是我不知道如何增加各个IP地址的值,这样我以后可以比较他们三个最常见的IP地址(这是我已经可以处理)。使用我的individualCounter变量,我希望能够以某种方式将其转换为整数值,但现在它总是与ipcounter相同,因为我编写的代码很差。
我在寻找的一个例子是:77.46.30.42出现59次,207.42.179.85出现46次,85.114.128.137出现19次。
我的一位同学建议我尝试设置,但是我觉得这样做并不能真正帮助我拉近距离,因为地图已经检查了重复内容。
看看这个,这将是一个很大的帮助,因为我猜测http://stackoverflow.com/questions/81346/最有效的方式增加a-map-value-in-java – piyushj