2011-02-28 183 views
2

我一直在做一個項目,在這個項目中我用Backus-Naur Form文法表示文件並用它生成句子。下面是BNF文件我工作過的:神祕的空指針

<s>::=<np> <vp> 
<np>::=<dp> <adjp> <n>|<pn> 
<pn>::=John|Jane|Sally|Spot|Fred|Elmo 
<adjp>::=<adj>|<adj> <adjp> 
<adj>::=big|fat|green|wonderful|faulty|subliminal|pretentious 
<dp>::=the|a 
<n>::=dog|cat|man|university|father|mother|child|television 
<vp>::=<tv> <np>|<iv> 
<tv>::=hit|honored|kissed|helped 
<iv>::=died|collapsed|laughed|wept 

幾乎一切工作正常,與隨時隨地的異常的字母「a」是通過規則集介紹。發生這種情況時,我收到以下錯誤:

Exception in thread "main" java.lang.NullPointerException at GrammarSolver.generate(GrammarSolver.java:95) at GrammarSolver.generate(GrammarSolver.java:109) at GrammarSolver.generate(GrammarSolver.java:116) at GrammarSolver.generate(GrammarSolver.java:116) at GrammarSolver.(GrammarSolver.java:51) at GrammarTest.main(GrammarTest.java:19)

我一直在努力追查並找到此錯誤的原因,但一直未能如願。因此,我正在尋求一些可能有更多經驗的人的建議,告訴我我的錯誤在哪裏,以便我能夠理解是什麼造成了錯誤,並避免在將來重複類似的錯誤。

我的程序代碼如下:

import java.util.*; 
import java.util.regex.*; 

class GrammarSolver { 

    //Create output variable for sentences 
    String output = ""; 

    //Create a map for storing grammar 
    SortedMap<String, String[]> rules = new TreeMap<String, String[]>(); 

    //Create a queue for managing sentences 
    Queue<String> queue = new LinkedList<String>(); 

    /** 
    * Constructor for GrammarSolver 
    * 
    * Accepts a List<String> then processes it splitting 
    * BNF notation into a TreeMap so that "A ::= B" is 
    * loaded into the tree so the key is A and the data 
    * contained is B 
    * 
    * @param  grammar  List of Strings with a set of 
    *       grammar rules in BNF form. 
    */ 
    public GrammarSolver(List<String> grammar){ 
     //Convert list to string 
     String s = grammar.toString(); 

     //Split and clean 
     String[] parts = s.split("::=|,"); 
     for(int i = 0; i < parts.length; i++){ 
      parts[i] = parts[i].trim(); 
      parts[i] = parts[i].replaceAll("\\[|]", ""); 
      //parts[i] = parts[i].replaceAll("[ \t]+", ""); 

     } 
     //Load into TreeMap 
     for(int i = 0; i < parts.length - 1; i+=2){ 
      String[] temp = parts[i+1].split("\\|"); 
      rules.put(parts[i], temp); 
     } 

     //Debug 
     String[] test = generate("<s>", 2); 
     System.out.println(test[0]); 
     System.out.println(test[1]); 
    } 

    /** 
    * Method to check if a certain non-terminal (such as <adj> 
    * is present in the map. 
    * 
    * Accepts a String and returns true if said non-terminal is 
    * in the map, and therefore a valid grammar. Returns false 
    * otherwise. 
    * 
    * @param  symbol  The string that will be checked 
    * @return  boolean  True if present, false if otherwise 
    */ 
    public boolean grammarContains(String symbol){ 
     if(rules.keySet().toString().contains(symbol)){ 
      return true; 
     }else{ 
      return false; 
     } 
    } 

    /** 
    * Method to generate sentences based on BNF notation and 
    * return them as strings. 
    * 
    * @param  symbol  The BNF symbol to be generated 
    * @param  times  The number of sentences to be generated 
    * @return  String  The generated sentence 
    */ 
    public String[] generate(String symbol, int times){ 
     //Array for output 
     String[] output = new String[times]; 

     for(int i = 0; i < times; i++){ 
      //Clear array for run 
      output[i] = ""; 

      //Grab rules, and store in an array 
      lString[] grammar = rules.get(symbol); 

      //Generate random number and assign to var 
      int rand = randomNumber(grammar.length); 

      //Take chosen grammar and split into array 
      String[] rules = grammar[rand].toString().split("\\s"); 

      //Determine if the rule is terminal or not 
      if(grammarContains(rules[0])){ 
       //System.out.println("grammar has more grammars"); 
       //Find if there is one or more conditions 
       if(rules.length == 1){ 
        String[] returnString = generate(rules[0], 1); 
        output[i] += returnString[0]; 
        output[i] += " "; 
       }else if(rules.length > 1){ 
        for(int j = 0; j < rules.length; j++){ 
         String[] returnString = generate(rules[j], 1); 
         output[i] += returnString[0]; 
         output[i] += " "; 
        } 
       } 
      }else{ 
       String[] returnArr = new String[1]; 
       returnArr[0] = grammar[rand];; 
       return returnArr; 
      } 
      output[i] = output[i].trim(); 
     } 
     return output; 
    } 

    /** 
    * Method to list all valid non-terminals for the current grammar 
    * 
    * @return  String  A listing of all valid non-terminals 
    *       contained in the current grammar that 
    *       can be used to generate words or 
    *       sentences. 
    */ 
    String getSymbols(){ 
     return rules.keySet().toString(); 
    } 

    public int randomNumber(int max){ 
     Random rand = new Random(); 
     int returnVal = rand.nextInt(max); 
     return returnVal; 
    } 
} 

和我的測試工具如下:

import java.io.*; 
import java.util.*; 

public class GrammarTest { 
    public static void main(String[] args) throws FileNotFoundException { 
     Scanner console = new Scanner(System.in); 
     System.out.println(); 

     // open grammar file 
     Scanner input = new Scanner(new File("sentence.txt")); 

     // read the grammar file and construct the grammar solver 
     List<String> grammar = new ArrayList<String>(); 
     while (input.hasNextLine()) { 
      String next = input.nextLine().trim(); 
      if (next.length() > 0) 
       grammar.add(next); 
     } 
     GrammarSolver solver = 
      new GrammarSolver(Collections.unmodifiableList(grammar)); 
    } 

} 

任何幫助或建議將不勝感激;

謝謝!

編輯:線95中,106和116關聯到

94 //generate random number and assign to var 
95  int rand = randomNumber(grammar.length); 
... 
105//Find if there is one or more conditions 
106 if(rules.length == 1){ 
... 
115 for(int j = 0; j < rules.length; j++){ 
116 String[] returnString = generate(rules[j], 1); 
+1

啊,那難以捉摸的NullPointerException。 95線是什麼? – Bozho 2011-02-28 21:39:33

+0

當我嘗試運行它時,它工作正常,你能發佈導致錯誤的句子.txt嗎?當我得到NPE幫助的時候,我做的事情是在地方添加「assert ___!= null」,以幫助隔離具體到來的內容爲空。 – 2011-02-28 21:44:23

+0

試圖從錯誤消息中同步代碼和行號,但它不起作用 - 不匹配。某些其他版本的文件產生了錯誤信息。請標記「第95行」。 (我猜這是這樣的:'int rand = randomNumber(grammar.length);') – 2011-02-28 21:48:41

回答

2

作爲第一步,我將確保

字符串[]語法= rules.get(符號);

不返回空值。這將消除像「grammar.length」和「grammar [rand] .toString()」這樣的可疑表達式。下一步是仔細檢查所有其他的解除引用爲空。

+0

我同意@mazaneicha,然後繼續進一步驗證變量的空值爲 – 2011-03-01 01:43:02

+0

非常感謝你們。當我意識到「a」正在通過遞歸過程時發現問題實際上源於grammarContains方法並使用報告誤報的String.contains(),因爲可以找到「a」所以我redid的方法,一切都很好! – Suki 2011-03-01 02:44:19

0

這並不直接回答你的問題,但我建議你使用一個IDE與一個集成的調試,如Eclipse

使用調試器可以讓您在發生異常時瞭解變量的狀態。這將允許您解決這樣的問題,而無需等待我們嘗試找出您的代碼。

+0

感謝您的建議!有沒有可以使用Eclipse調試器的指南或教程? – Suki 2011-02-28 22:30:18

+0

這[YouTube視頻](http://www.youtube.com/watch?v=WeSitNPAExg)看起來不錯。 – GavinH 2011-02-28 22:45:52

0

rules不包含您的終端(一),似乎。嘗試rules.get("a")時失敗,因爲它返回null

我也推薦使用例如蝕進行調試 - 可以很容易地逐步執行堆棧幀時崩潰:-)