Java 检查用户输入是否包含项目

Java 检查用户输入是否包含项目,java,Java,在我的文本冒险游戏中,其中一个命令是“take”,它要求用户输入字母“T”和他们所在房间中的物品。 我已经接受了这个输入,并将其分为命令和项,但if语句有问题。我有第一部分检查命令部分是否等于'T',但是我还必须检查这个输入是否有一个“item”部分。我试过使用.isEmpty()和!=null以及使用.contains() 这是我的密码: public Command getCommandFromResponse(String response) throws IllegalArgumentE

在我的文本冒险游戏中,其中一个命令是“take”,它要求用户输入字母“T”和他们所在房间中的物品。
我已经接受了这个输入,并将其分为命令和项,但if语句有问题。我有第一部分检查命令部分是否等于'T',但是我还必须检查这个输入是否有一个“item”部分。我试过使用
.isEmpty()
!=null
以及使用
.contains()

这是我的密码:

public Command getCommandFromResponse(String response) throws IllegalArgumentException{
    String[] split = response.split(" ");

    if (split.length < 1){
        throw new IllegalArgumentException("Invalid command.");
    }

    Command command = new Command(split[0]);
    if (split.length >= 2) {
        command.setItem(split[1]);
    }
    return command;
}
这是我的命令类:

public class Command {

    String command;
    String item;
    public Command(String comm){
        command = comm;
    }

    public Command(String comm, String item){
        this.command = comm;
        this.item = item;
    }

    public void setCommand(String command){
        this.command = command;
    }

    public void setItem(String item){
        this.item = item;
    }

    public String getCommand(){
        return this.command;
    }

    public String getItem(){
        return this.item;
    }

    public String toString(){
        return this.command + ":" + this.item;
    }

}
这些是我的物品:

//Items {itemName, itemDes}
    static Item[] items = {
            new Item ("map","a layout of your house", 10 ),
            new Item ("battery", "a double A battery", 5),
            new Item ("flashlight", "a small silver flashlight", 10),
            new Item ("key", "this unlocks some door in your house", 15),
    };

如果不清楚,我有更多的代码。

我的建议是按以下方式执行:

改变

if (userCommand.item.equalsIgnoreCase(locale.item.itemName)) {

这是最简单的方法,如果命令中没有项,则不会引发异常


(如果这不是您的问题,我很抱歉,但我认为您的意思是,这就是问题所在。)

如何存储所有项目?名单?Enum?我有一个Item类,项目存储在一个Item数组中。我在上面的代码中添加了它们:)您遇到了什么错误?如果用户输入例如:t map,那么它将在我的游戏中显示无效命令。如果我使用userCommand.item!=null然后我得到一个nullpointer异常。谢谢,唯一的问题是我必须首先检查t,以及在t之后是否输入了第二个单词,然后下一步是检查输入的第二个单词是否是房间中存在的项目。通过使用userCommand.item!=null我得到了一个nullpointerexception。如果您正好在这个位置(在
userCommand.item
)得到了一个“nullpointerexception”,那么“userCommand”似乎有问题。检查它是否已正确初始化。当我在游戏中输入命令并按enter键时,会有一个空格,如果我再次按enter键,则会出现异常,因此我对出错的地方有点茫然。我认为这一行是问题所在:
else if(userCommand.command.equalsIgnoreCase(“T”)&&&/*if userCommand包含一个item*/){//将输入字符串分成两部分,command和item userCommand=getCommandFromResponse(userInput.nextLine());
userCommand似乎在
else if
-子句中初始化。然后,再次读取输入(
userInput.nextLine()
)这显然只会返回一个空行。我建议删除这一行:
userCommand=getCommandFromResponse(userInput.nextLine());
if (userCommand.item.equalsIgnoreCase(locale.item.itemName)) {
if (userCommand.item!=null && userCommand.item.equalsIgnoreCase(locale.item.itemName)) {