2016-05-18 31 views
0

所以我完全停留在我的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次。

我的一位同学建议我尝试设置,但是我觉得这样做并不能真正帮助我拉近距离,因为地图已经检查了重复内容。

+0

看看这个,这将是一个很大的帮助,因为我猜测http://stackoverflow.com/questions/81346/最有效的方式增加a-map-value-in-java – piyushj

回答

1

你可以做这样的事情:

if(ipCheck.containsKey(s2)){ 
    ipCheck.put(s2, ipCheck.get(s2)+1); 
}else{ 
    ipCheck.put(s2, 1); 
} 

这样做是要检查IP已经在地图上,如果是,它得到前一计此IP,并通过增加其一,如果它不是,它将它添加到地图,并将其计数设置为1.

+0

if语句以“操作++/- 的无效参数”消息响应我。你确定格式正确吗? – Tyler

+0

@泰勒哦,你说得对,我编辑了我的问题来解决这个问题。 – Titus

+0

好吧,所以现在它正在适当地改变它为每个IP的价值之一。但是,每次运行副本时都不会增加它。检查重复项是否能够进一步增加计数器,还是仅仅停留在一个? 209.129.94.61例如弹出10次,但它只提供1. – Tyler