В моем тексте-адвенчуры одна из команд «взять», которая требует от пользователя ввести как буква «T» и элемент, который находится в комнате, они in.
Я взял этот ввод и разделил его на команду и элемент, но у меня возникли проблемы с оператором 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
Это моя команда класс:
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),
};
У меня есть больше кода, если это неясно.
Как вы сохранили на все элементы? Список? Enum? – bwfcwalshy
У меня есть класс Item, и элементы хранятся в массиве Item. Я добавил их к моему коду выше :) – user5959738
Какая ошибка вы получаете? – BPS