在 Java 中,如何在 while 循环中修复此 nullPointerException?

In Java, how can I fix this nullPointerException in a while loop?

在 java 文件中,我一直在带有 while 循环的行中遇到运行时错误 Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException,我需要找到一种方法来避免此 nullPointerException。

我当前在这一行的代码如下所示:

while (b.isOnBoard(row-i, col-i) && b.getState(row-i, col-i).equals(yourcolor))
{
    count++; 
    i++;
}

对象 b 基本上是 othello 游戏的 8 x 8 矩阵 "board"。方法 isOnBoard 将 return 一个布尔值,方法 getState 将 return 我的玩家颜色,我的对手颜色(yourcolor),或 null.我不明白为什么这些 returning null 中的任何一个都会导致 nullPointerException。 谁能告诉我是什么原因导致此错误以及如何解决?非常感谢任何帮助。

the method getState will return either my players color, my opponents color(yourcolor), or null

如果 getState returns 为 null,如您所说,b.getState(row-i, col-i).equals(yourcolor) 将抛出 NullPointerException.

要避免它,请将条件更改为:

while (b.isOnBoard(row-i, col-i) && b.getState(row-i, col-i) != null && b.getState(row-i, col-i).equals(yourcolor))

当然,如果 b 可能为空(根据您提供的少量代码无法判断),那也会导致 NullPointerException.

问题是您的 getState() 方法可以 return 一个 null 并且您在其上调用 equals()

你永远不应该 return nullnull 不是一个值。使用枚举或其他 return 类型。