2013-03-12 5 views
3

로그 파일을 읽고 특정 문자열이 표시되는 횟수를 계산하는 프로그램을 작성 중입니다. 나는 수동으로 문자열을 키워드로 입력하려고했으나 너무 많이 있기 때문에 로그 파일을 검색하는 것이 더 좋을 것이라고 판단하고 "ua"를 만나면 "ua"에서 새 문자열을 만들어야합니다. 줄의 끝을 해시 맵에 추가하고 해당 특정 문자열 ("ua"로 시작하는 모든 문자열)에 대한 수를 늘립니다. 해시 맵에 새 문자열을 추가하는 방법을 알아낼 수 없습니다. 이것은 내가 지금까지 가지고있는 것이다.새로운 문자열을 해시 맵에 추가하기 자바

public class Logs 
{ 

public static void main(String args[]) throws IOException 
{ 

Map<String, Integer> dayCount = new HashMap<String, Integer>(); 
    for (String str : KeyWords) 
    { 
     dayCount.put(str, 0); 
    } 

    File path = new File("C:\\P4logs"); 
    for(File f: path.listFiles()) 
    { // this loops through all the files + directories 

     if(f.isFile()) 
     { // checks if it is a file, not a directory. 

    try (BufferedReader br = new BufferedReader(new FileReader(f.getAbsolutePath()))) 
    { 


String sCurrentLine; 

while ((sCurrentLine = br.readLine()) != null) 
{ 
    boolean found = false; 

    for (String str : DayCount.keySet()) 
    { 
     if (sCurrentLine.indexOf(str) != -1) 
     { 
      DayCount.put(str, DayCount.get(str) + 1); 
      found = true; 
      break; 
     } 
    } 
    if (!found && sCurrentLine.indexOf("ua, ") != -1) 
    { 
     System.out.println("Found an unknown user action: " + sCurrentLine); 
     DayCount.put(key, value) //not sure what to put here 
    } 
    } 
    } 
for(String str : KeyWords) 
    { 
     System.out.println(str + " = " + DayCount.get(str)); 

    } 

    } 
    } 
} 

}

+0

무엇을 넣어야할지 모르시겠습니까? .... 다른 곳에 두는 것만 넣으면됩니다. – Colleen

+0

** DayCount ** 란 무엇입니까? 어떻게 그리고 어디에서 정의됩니까? –

+0

'DayCount'는 표준'HashMap'입니까? – iamnotmaynard

답변

7

당신은 하나가 존재하는지 확인하기 위해 해시 맵의 키를 반복 할 필요가 없습니다! 이는 해시 맵 (목적 코드가 인데 O(1)과 충돌하지 않음)을 사용하는 목적을 무효로 만듭니다. 다음과 같이하면됩니다.

//If a key doesn't exist in a hashmap, `get(T)` returns null 
if(DayCount.get(str) == null) { 
    //We know this key doesn't exist, so let's create a new entry with 1 as the count 
    DayCount.put(str, 1); 
} else { 
    //We know this key exists, so let's get the old count, increment it, and then update 
    //the value 
    int count = DayCount.get(str); 
    DayCount.put(str, count + 1); 
} 

또 다른 점은 Java 명명 규칙을 따르는 것입니다. 변수는 소문자로 시작해야합니다 (즉, dayCountDayCount). 클래스는 대문자로 시작해야합니다. 당신이 지금 가지고있는 방법, DayCountput이라는 정적 메서드를 가진 클래스입니다.

it should create a new string from "ua, " to the end of the line 

라인이 "UA,"또는로 시작하면 그것은 분명하지 않다 때문에 "UA,"라인의 중간에있을 수 있습니다 -이 이후

+0

@Vivian Paliath 흠 괜찮아요.하지만 str은 마치 아무것도 위에 반복하지 않는 것처럼 정의해야합니까? – user2007843

+0

@ user2007843 방금'str'을 플레이스 홀더로 사용했습니다. 파일에서 읽은 행에서 개별 문자열을 가져와야합니다 (기본적으로'sCurrentLine'을 나눕니다). 나는 당신이 개별적인 단어 나 그와 비슷한 것을 셀 수 있다고 가정하고 있습니다. –

+0

@Vivian Paliath 내가 셀 수있는 예는''ua, login, reboot ''입니다. – user2007843

0

귀하의 요구 사항입니다. 이것은 아마도 어떻게 보일까요? -

while ((sCurrentLine = br.readLine()) != null) 
    { 

     if(sCurrentLine.indexOf("ua, ") != -1){ 
      String str = sCurrentLine.substr("ua, "); 
      if(dayCount.get(str) != null){ 
        dayCount.put(str, dayCount(str) +1); 
       }else{ 
        dayCount.put(str, 1); 
       } 
     } 

    } 
관련 문제