So I am completely stuck on a homework assignment for my java class. In it, I need to write a program that analyzes a web server's log file to determine which computers have attempted to access that web server the most. I have chosen to use a map to track the files that are ran with it in order to save each unique address with an integer value that would increase each time the code finds a duplicate IP address.
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");
}
}
}
The issue I am facing is I am not sure how to increase the value of each individual IP address, so that I can later compare them for the three most frequent IP addresses (something I can already handle). With my individualCounter variable, I was hoping to be able to somehow coax that into the integer value, but as it stands now, it will always be the same as ipcounter due to how poorly I have it coded.
An example of what I am looking for is: 77.46.30.42 appears 59 times, 207.42.179.85 appears 46 times, and 85.114.128.137 appears 19 times.
One of my classmates has suggested I try set, but I feel like that would not really help me get any closer, as map already checks for duplicates.