在我的文字冒險遊戲的命令之一是「拿」這需要用戶輸入兩個字母「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;
}
這是take方法:
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
這是我的命令類:
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),
};
我有更多的代碼,如果這不清楚。
的所有項目?一個列表?枚舉? – bwfcwalshy
我有一個Item類,這些Items存儲在一個Item數組中。我將它們添加到我的代碼:) – user5959738
你得到什麼錯誤? – BPS