2012-01-17 3 views
4

내 작은 프로젝트는 임의의 .java 파일에있는 모든 단어를 가져와 파일에 나타나는 모든 행을 나열해야하는 어휘 분석 프로그램입니다. 나는 예약어에 표를 한개 씩 올려야하고, 문서에있는 모든 추가 단어를 표기해야한다. 이처럼 것은 프로그램처럼 : 출력해야간단한 어휘 분석 java 프로그램

public class xxxx { 
    int xyz; 
    xyz = 0; 
} 

:

Reserved words: 
class: 1 
int: 2 
public: 1 

Other words: 
xxxx: 1 
xyz: 2, 3 

그러나 개정 그래서에, 거기에 많은 문제가 나의 현재의 프로그램이며, 그래서 난 세드릭 아무 생각이 내 프로그램이나 완전 재 작성을 환영합니다. 나는 자바 언어를 취미로 사용하려고 노력하고있어, 무슨 일이 벌어지는 지 이해할 수만 있다면 모든 도움을 환영한다. 나는 거기에이 문제에 대한 간단한 해결책은 있지만 확신 도움 ^^

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 
import java.util.Scanner; 

public class LexicalAnalysis { 

    private String[] keywords = { "abstract", "boolean", "byte", "case", 
      "catch", "char", "class", "continue", "default", "do", "double", 
      "else", "extends", "final", "finally", "float", "for", "if", 
      "implements", "import", "instanceof", "int", "interface", "long", 
      "native", "new", "package", "private", "protected", "public", 
      "return", "short", "static", "super", "switch", "synchronized", 
      "this", "throw", "throws", "transient", "try", "void", "volatile", 
      "while", "false", "true", "null" }; 
    HashMap<String, ArrayList<Integer>> keywordsTable; 

    HashMap<String, ArrayList<Integer>> otherWords = new HashMap<String, ArrayList<Integer>>(); 

    public LexicalAnalysis(String fileName){ 

     Scanner kb = null; 
     int lineNumber = 0; 

     try { 
      kb = new Scanner(new File(fileName)); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

      keywordsTable = new HashMap<String, ArrayList<Integer>>(); 
      for(int i = 0; i < 47; i++){ 
       keywordsTable.put(keywords[i], new ArrayList<Integer>()); 
      } 

     while(kb.hasNextLine()){ 

      lineNumber++; 

      String line = kb.nextLine(); 

      String[] lineparts = line.split("\\s+|\\.+|\\;+|\\(+|\\)+|\\\"+|\\:+|\\[+|\\]+"); 

      for(String x: lineparts){ 

       ArrayList<Integer> list = keywordsTable.get(x); 
       if(list == null){ 
        list = otherWords.get(x); 
        if(list == null){ 
         ArrayList<Integer> temp = new ArrayList<Integer>(); 
         temp.add(lineNumber); 
         otherWords.put(x,temp); 
        }else{ 
         otherWords.remove(x); 
         ArrayList<Integer> temp = new ArrayList<Integer>(); 
         temp.add(lineNumber); 
         otherWords.put(x, temp); 
        } 
       }else{ 
        keywordsTable.remove(x); 
        ArrayList<Integer> temp = new ArrayList<Integer>(); 
        temp.add(lineNumber); 
        keywordsTable.put(x, temp); 
       } 
      } 
     } 
     System.out.println("Keywords:"); 
     printMap(keywordsTable); 
     System.out.println(); 
     System.out.println("Other Words:"); 
     printMap(otherWords); 

    } 
    public static void printMap(Map<String, ArrayList<Integer>> mp) {  
     Iterator<Map.Entry<String, ArrayList<Integer>>> it = mp.entrySet().iterator();  
     while (it.hasNext()) {   
      Map.Entry<String, ArrayList<Integer>> pairs = (Map.Entry<String, ArrayList<Integer>>)it.next();  
      System.out.print(pairs.getKey() + " = "); 
      printList(pairs.getValue()); 
      System.out.println(); 
      it.remove(); 
     } 
    } 
    public static void printList(List x){ 

     for(Object m : x){ 
      System.out.print(m + ", "); 
     } 

    } 
    public static void main(String args[]){ 
     new LexicalAnalysis("lexitest.txt"); 
    } 


} 
+0

무엇이 문제입니까? 예를 들어주세요. – paislee

+0

위의 예제를 실행하면 공백과 대괄호도 실행됩니다. 또한 단어가 나타나는 각 위치의 위치가 추가되지 않으므로 null이 8 번 나타나면 한 번만 표시됩니다. = ( – user1152918

+0

정규식이 필요해 보이지만, 정규 표현식을 사용하면 puncuation 문자가없는 단어 만 얻을 수 있으므로 구두점이있는 모든 단어는 무시됩니다. – user1152918

답변

1

이를위한 가장 간단한 방법은 올바른 렉스 파일 정의 키워드 JFlex를 사용하는 것입니다에 대한 :(감사를 작동하지 않았다 내 시도 일단 당신이 그것을 가지고, 식별자와 키워드를 세는 것은 간단합니다.

0

나는 모든 것을 고쳤다고 생각하는 버그 하나를 발견했습니다. 당신이 당신의 메인에 복구하는 파일의 디렉토리를 명시해야합니다. 새로운 LexicalAnalysis ("lexitest.txt");

내 예제에서 나는 새로운 LexicalAnalysis ("F"\ lexitest.txt ")가되도록 내 flashdrive를 사용하고 있습니다. ;