gpt4 book ai didi

java - 是什么导致了我的 NullPointerException?

转载 作者:行者123 更新时间:2023-12-01 06:28:43 25 4
gpt4 key购买 nike

我的程序编译完美,但每当我尝试运行时,它都会抛出 NullPointerException。我尝试对此进行搜索,发现该错误与程序尝试使用某些值为空的值有关,但我重新检查了所有内容,结果却是空白。

错误如下:

java.lang.NullPointerException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:27‌​2)

代码:

import javax.swing.*;
import java.util.Scanner;

public class WorldsMostBoringGame
{
public void main (String [] args)
{
System.out.println("You are in a room with a locked door and a key.");

Scanner keyboard = new Scanner(System.in);
boolean hasKey = false, doorOpen = false, amIDoneYet = false, monsterAlive = true;

while (!amIDoneYet)
{
String userInput = keyboard.nextLine();

if (userInput == "look around")
LookAround(hasKey);
else if (userInput == "get key")
GetKey(hasKey, monsterAlive);
else if (userInput == "open door")
OpenDoor(doorOpen, hasKey, amIDoneYet);
else if (userInput == "kill monster")
KillMonster(monsterAlive);
else
System.out.println(userInput+ " is not a recognized command.");
}
}

public boolean GetKey(boolean hasKey, boolean monsterAlive)
{
if (hasKey == false && monsterAlive == false)
System.out.println("You pick up the key.");
else if (hasKey == true && monsterAlive == false)
System.out.println("You already picked up the key.");
else if (monsterAlive == true)
{
System.out.println("You must kill the monster first.");
return hasKey = false;
}

return hasKey = true;
}

public void LookAround(boolean hasKey)
{
if (!hasKey)
System.out.println("You are in a room with a locked door and a key.");
else
System.out.println("You are in a room with a locked door. You have a key.");
}

public boolean OpenDoor(boolean doorOpen, boolean hasKey, boolean amIDoneYet)
{
if (hasKey)
{
System.out.println("You unlock the door. Game over. You win.");
amIDoneYet = true;
return doorOpen;
}
else
{
System.out.println("The door is locked. Find a key.");
return doorOpen = false;
}
}

public boolean KillMonster(boolean monsterAlive)
{
System.out.println("You kill the monster.");
return monsterAlive = false;
}
}

最佳答案

main 方法添加 static 关键字,以便应用程序具有有效的入口点

public static void main (String [] args) {

编辑:

完成此更改后,创建 WorldsMostBoringGame 的实例,以便可以调用实例方法:

WorldsMostBoringGame game = new WorldsMostBoringGame(); // create this instance
while (!amIDoneYet) {
String userInput = keyboard.nextLine();
if ("look around".equals(userInput)) { // use String.equals
game.lookAround(hasKey);
} ...

关于java - 是什么导致了我的 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19639150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com