【问题标题】:Mysterious NullPointer神秘的空指针
【发布时间】:2011-02-28 21:37:44
【问题描述】:

我一直在从事一个项目,在该项目中,我使用 Backus–Naur 形式语法符号获取一个文件并用它生成句子。这是我正在处理的 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”的任何时候,几乎一切都运行良好。发生这种情况时,我收到以下错误:

线程“main”中的异常 java.lang.NullPointerException 在 GrammarSolver.generate(GrammarSolver.java:95) 在 GrammarSolver.generate(GrammarSolver.java:109) 在 GrammarSolver.generate(GrammarSolver.java:116) 在 GrammarSolver.generate(GrammarSolver.java:116) 在 GrammarSolver.(GrammarSolver.java:51) 在 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);

【问题讨论】:

  • 啊,那个难以捉摸的 NullPointerException。第 95 行是什么?
  • 当我尝试运行它时,它运行良好,你能发布一个导致错误的 sentence.txt 吗?当我得到 NPE 有帮助时,我会做的事情是在一些地方添加“assert ___!= null”,以帮助隔离具体的内容为 null。
  • 尝试从错误消息中同步代码和行号,但它不起作用 - 不匹配。该文件的某些其他版本产生了错误消息。请标记“第 95 行”。 (我猜是这个:int rand = randomNumber(grammar.length);
  • 我添加了一个编辑来匹配行号和行。非常感谢到目前为止的帮助!
  • 语法对我来说是空的,但只有当 sentence.txt 文件不是格式正确的语法时才会发生这种情况。

标签: java arrays recursion


【解决方案1】:

作为第一步,我会确保

String[] 语法 = rules.get(symbol);

不返回空值。这将消除像“grammar.length”和“grammar[rand].toString()”这样的可疑表达。下一步将仔细检查所有其他取消引用是否为 null。

【讨论】:

  • 我同意@mazaneicha,在继续针对空值进一步验证变量之前
  • 非常感谢你们。当我意识到“a”通过递归传递时,我正在遵循这个建议,并发现问题实际上源于 GrammarContains 方法并使用 String.contains() 报告误报,因为可以找到“a”,所以我重做了方法,一切都很好!
【解决方案2】:

这并不能直接回答您的问题,但我建议您使用带有集成调试器的 IDE,例如 Eclipse

使用调试器可以让您深入了解异常发生时变量的状态。这将允许您解决此类问题,而无需等待我们尝试找出您的代码。

【讨论】:

  • 感谢您的建议!是否有使用 Eclipse 调试器的指南或教程?
  • 这个YouTube video 看起来不错。
【解决方案3】:

rules 似乎不包含您的终端 (a)。尝试rules.get("a") 时失败,因为它返回null

我还建议使用例如用于调试的 Eclipse - 可以在崩溃时轻松单步执行堆栈帧:-)

【讨论】: