遇到java.lang.NullPointerException

莎兰妮·古普塔(Saranya Gupta)

关于Java中的上述错误,我已经看到许多答案,但是大多数答案都在告诉错误是什么,而我找不到纠正它的方法。

这是我的Java代码片段:

public static void optimalAlignmentScoreBU(String r, String s, int matchScore, int transition, int transversion, int indel) {

        int m = r.length();
        int n = s.length();
        Node[][] strg = new Node[m + 1][n + 1];

        // base cases
        strg[m][n].val = 0;
}

在写strg [m] [n] .val = 0的那一行出现错误。我创建了一个Node类,如下所示:

// ELEMENT OF DP MATRIX IS OF TYPE NODE
    public class Node {
        int val;
        ArrayList<Pair<Integer>> arrows = new ArrayList<Pair<Integer>>();
    }

// PAIR CLASS
public static class Pair<T> {
        T p1;
        T p2;

        public Pair(T p1, T p2) {
            this.p1 = p1;
            this.p2 = p2;
        }
    }

你能告诉我出什么事了吗?为什么要指出NULL?我该怎么做才能纠正这个问题?

乔普·艾根(Joop Eggen)

您创建了一个空节点矩阵。

    strg[m][n] = new Node();
    strg[m][n].val = 0; // Now there is a Node, no longer NPE.

当然更好的是:

    Node node = new Node();
    node.val = 0;
    strg[m][n] = node;

新节点实际上具有val字段的地方已经为0。

当然,必须创建所有矩阵节点。

在Java中:

int[] v = new int[10]; // All 0.
boolean[] v = new boolean[10]; // All false.
String[] v = new String[10]; // All null.
double[] v = new double[10];  // All 0.0.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章