所以我正在尝试创建一款游戏。我的主要方法调用我放置在同一文件中的另一个方法。测试时它工作得非常好,但由于某种原因它停止工作并向我抛出一个 NPE。作为前言,我非常新手(仅了解我的 Java 教科书的第 5 章)。
这是我的代码的相关部分。我将信息从我的主方法传递到另一个方法,该方法使用另一种方法进行计算。此方法传递了对包含字符串的游戏板对象的引用。如果我向 PushCard 方法传递一个常量而不是 getSlot** 方法,则它可以正常工作。 NPE 是否意味着我引用的 newBoard 对象已变为 null?如果我在调用 WindAction() 之前放置 System.out.print,它会打印正确的字符串而不是 null。我很困惑。
任何帮助或建议都会有很大帮助。提前致谢。
public static void main (String[] args)
{
switch (playCard)
{
case "wind":
//slotselection has already been given a value
windAction(slotSelection.toUpperCase());
break;
// There is more code here that is not shown...............
}
}
public static void windAction(String slotSelection)
{
switch (slotSelection.toUpperCase())
{
case "A1":
{
if (pushCard(newBoard.getSlotA2(), newBoard.getSlotA3()) == true)
newBoard.setSlotA3(newBoard.getSlotA2());
newBoard.setSlotA2("EMPTY");
if (pushCard(newBoard.getSlotB1, newBoard.getSlotC1) == true)
newBoard.setSlotC1(newBoard.getSlotB1());
newBoard.setSlotB1("EMPTY");
} //end case A1
break;
// There is more code here that is not shown...............
}
}
public static Boolean pushCard(String S1, String S2)
{
Boolean result = null;
if ((S1 == "fire") | (S1 == "water") | (S1 == "wind")){
if ((S2 != "fire") | (S2 != "water") | (S2 != "wind"))
result = true;
else
result = false;
}
return result;
}//end push card method
最佳答案
我相信 NullPointerException 可能是由您的 pushCard
方法引起的 -> 您正在使用 Boolean 类而不是 boolean 基元,并且在某些情况下它可能为 null。
您正在使用按位或操作来检查逻辑或,并且您正在使用 == 检查字符串相等性,这将导致 if 语句失败,因此不会设置结果:
Boolean result = null;
if ((S1 == "fire") | (S1 == "water") | (S1 == "wind")){
...
}
应该是:
boolean result = false;
if ("fire".equals(S1) || "water".equals(S1) || "wind".equals(S1)){
...
}
必须对其中的 if 语句进行类似的更改。
关于java - 调用与 main 方法在同一文件中的方法时出现 NullpointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18005869/