增加HashMap中的单个值

时间:2016-05-18 05:49:38

标签: java dictionary hashmap set keyvaluepair

所以我完全陷入了我的java课程的家庭作业。在其中,我需要编写一个程序来分析Web服务器的日志文件,以确定哪些计算机最多尝试访问该Web服务器。我选择使用映射来跟踪使用它运行的文件,以便使用整数值保存每个唯一地址,该值在每次代码找到重复的IP地址时都会增加。

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次。

我的一个同学建议我尝试设置,但我觉得这不会真正帮助我更接近,因为地图已经检查了重复。

1 个答案:

答案 0 :(得分:1)

您可以这样做:

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

这样做是为了检查IP是否已经在地图中,如果是,它获取此IP的先前计数,并将其递增1,如果不是,则将其添加到地图并设置它的数量为1。