在我的文本冒险游戏中,其中一个命令是“take”,这要求用户同时输入字母'T'以及其中的一个项目他们在的房间。
我已经把这个输入分成了命令和项目,但我遇到了if语句的问题。我有第一部分检查命令部分是否等于'T',但我还要检查此输入是否有一个“项目”部分。我尝试使用.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;
}
这是采取方法:
else if(userCommand.command.equalsIgnoreCase("T") && /*if userCommand contains an item*/){
//Split the input String into two parts, command and item
userCommand = getCommandFromResponse(userInput.nextLine());
if (locale.item != null) {
if (userCommand.item.equalsIgnoreCase(locale.item.itemName)) {
//add the item to the player's inventory
player1.inventory.add(locale.item);
System.out.println("\tA " + locale.item + " was added to your inventory");
System.out.println("\n\tYou can view your inventory by pressing 'I' or drop an item by pressing 'D'.");
if (locale.item.itemName.equals("map")) {
System.out.println("\n\tTo view the map press 'M'.");
}
//Add the item's worth to the score and set the items worth to zero to prevent double scoring
player1.score += locale.item.value;
System.out.println("\n\t" + locale.item.value + " points have been added to your score.");
System.out.println("\n\tThis is your current score: "+player1.score);
//remove the item from the current location
locale.item = null;
break;
} else {
System.out.println("\n\tThat item is not at this location.");
}
} else {
System.out.println("\n\tThere is no item to pick up here");
}
}//End of Take
这是我的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),
};
如果不清楚,我会有更多代码。
答案 0 :(得分:0)
我的建议是按照以下方式进行:
变化
if (userCommand.item.equalsIgnoreCase(locale.item.itemName)) {
到
if (userCommand.item!=null && userCommand.item.equalsIgnoreCase(locale.item.itemName)) {
这是最简单的方法,如果命令中没有项目,则不会抛出异常。
(如果这不是你的问题,我很抱歉,但这就是我认为你的意思。)