显示java.lang.NullPointerException

时间:2011-07-10 22:07:17

标签: java nullpointerexception

我一直得到这个例外:

Exception in thread "Thread-1" java.lang.NullPointerException
        at Info.<init>(Info.java:168)
        at Rcon.data(Rcon.java:130)
        at Rcon$1.run(Rcon.java:105)

第168行是bot.redScore = Integer.parseInt(matcher.group(2));

    else if(str.indexOf("current score") != -1) {
        pattern = "Team \\\"(\\w+)\\\" current score \\\"(\\d+)\\\"";
        p = Pattern.compile(pattern);
        matcher = p.matcher(str);
        if(matcher.find()) {
            if(matcher.group(1).equalsIgnoreCase("Red")) {
                bot.redScore = Integer.parseInt(matcher.group(2));

            }
            else if(matcher.group(1).equalsIgnoreCase("Blue")) {
                bot.blueScore = Integer.parseInt(matcher.group(2));
            }
            cmd = "score";
        }
    }

我不知道为什么我一直收到这个错误。 使用正则表达式解析的str是:

Processing: Team "Red" current score "1" with "1" players

当我自己只运行这部分时,它运行正常。 但是当我运行整个程序时,我得到了这个例外。

bot.blueScore和bot.redScore正在另一个类中声明如下:

int redScore = 0;
int blueScore = 0;

我还检查了matcher.group(2)的内容,它返回一个整数,从0到10。 有任何想法吗?我一直在努力工作几个小时。

谢谢!

2 个答案:

答案 0 :(得分:4)

bot可能是null。确保它不为null(初始化)

那就是说,你应该学会阅读例外 - 这是一项非常核心的技能。 NullPointerException是最常见的例外 - 您已经识别了该行,如果您检查了该异常的文档,您会看到它通常在引用为null并且您尝试访问方法时发生/字段就可以了。

答案 1 :(得分:2)

如果获得空指针异常,请查找表单x.y行上的表达式,并问自己为什么x为空。在您的情况下,botmatcher必须为空。由于您在前一行使用matcher进入该行,因此您的变量bot为空。

相关问题