我不断收到此异常:
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 之间。 有任何想法吗?我已经为此苦苦挣扎了几个小时。
谢谢!
最佳答案
bot
可能为 null
。确保它不为空(初始化它)
也就是说,您应该学会阅读异常 - 这是一项非常核心的技能。 NullPointerException
是最常见的异常 - 您已经识别了该行,如果您检查异常的文档,您会发现它通常发生在引用为 null
且您正在尝试访问其上的方法/字段。
关于java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6644056/