Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 神秘的零指针_Java_Arrays_Recursion - Fatal编程技术网

Java 神秘的零指针

Java 神秘的零指针,java,arrays,recursion,Java,Arrays,Recursion,我一直在做一个项目,在这个项目中,我用Backus–Naur格式的语法符号获取一个文件,并用它生成句子。这是我正在处理的BNF文件: <s>::=<np> <vp> <np>::=<dp> <adjp> <n>|<pn> <pn>::=John|Jane|Sally|Spot|Fred|Elmo <adjp>::=<adj>|<adj> <adjp

我一直在做一个项目,在这个项目中,我用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
:=
::=  |
::=John | Jane | Sally | Spot | Fred | Elmo
::=| 
::=大|胖|绿|棒|错|潜意识|自命不凡
:=a
::=狗|猫|人|大学|父亲|母亲|孩子|电视
::= |
::=击中|荣誉|亲吻|帮助
::=死了|倒了|笑了|哭了
除了通过规则集引入字母“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)

我一直在尝试跟踪和定位此错误的原因,但无法做到这一点。因此,我正在寻求一位可能更有经验的人的建议,让我知道我的bug在哪里,这样我就可以理解是什么导致了它,并避免将来重复类似的错误

我的程序代码如下所示:

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));
    }

}
import java.util.*;
导入java.util.regex.*;
类语法工具{
//为句子创建输出变量
字符串输出=”;
//创建用于存储语法的映射
SortedMap规则=新树映射();
//创建用于管理句子的队列
Queue Queue=new LinkedList();
/**
*GrammarSolver的构造函数
*
*接受一个列表,然后处理它
*将BNF符号转换成树形图,这样“a::=B”是
*加载到树中,使键为
*包含的是B
*
*@param语法字符串列表,包含一组
*BNF形式的语法规则。
*/
公共语法Solver(列表语法){
//将列表转换为字符串
字符串s=语法.toString();
//干干净净
字符串[]部分=s.split(“::=|,”;
对于(int i=0;i1){
对于(int j=0;j
我的测试线束如下所示:

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));
    }

}
import java.io.*;
导入java.util.*;
公共课语法{
公共静态void main(字符串[]args)引发FileNotFoundException{
扫描仪控制台=新扫描仪(System.in);