Java按字符串搜索对象
我有一个班级项目 并创建多个对象(树、电视、书籍等) 在课堂游戏中Java按字符串搜索对象,java,object,Java,Object,我有一个班级项目 并创建多个对象(树、电视、书籍等) 在课堂游戏中 // Create the items tree = new Item("tree", "I big green tree", 60); coat = new Item("coat", "I white coat", 5); paper = new Item("paper", "a role of wc paper", 1); 现在
// Create the items
tree = new Item("tree", "I big green tree", 60);
coat = new Item("coat", "I white coat", 5);
paper = new Item("paper", "a role of wc paper", 1);
现在,玩家(也是玩家类)必须保存一些物品。
玩家可以通过键入:get book获得此项,其中book是字符串secondWord
现在我需要在类游戏中使用一个函数
由字符串组成的对象
比如,
玩家进入记录簿
player1.takeItem(Item secondWord);
在player类中,我有一个函数takeItem()
但这不起作用。希望您能帮助我我假设您的课程
项目
如下所示:
public class Item {
private String kind;
private String description;
private int price;
public Item(String kind, String description, int price) {
this.kind = kind;
this.description = description;
this.price = price;
}
...
}
然后,在Item
类中,您可以简单地创建一个方法,该方法以字符串形式返回项的类型
public String getKind() {
return this.kind;
}
我猜你在某处有一张所有物品的清单。然后,您可以使用getItem(String)
从列表中轻松获取项目,它返回所需的项目
private List<Item> items = new ArrayList<Item>() {{
add(new Item("tree", "I big green tree", 60));
add(new Item("coat", "I white coat", 5));
add(new Item("paper", "a role of wc paper", 1));
}};
public Item getItem(String itemName) {
for (Item item : this.items) {
if (item.getKind().equals(itemName)) {
return item;
}
}
return null;
}
private List items=new ArrayList(){{
添加(新项目(“树”,“我的大绿树”,60));
添加(新项目(“涂层”、“I白色涂层”,5));
增加(新项目(“文件”,“wc文件的角色”,1));
}};
公共项getItem(字符串itemName){
用于(项目:此.items){
if(item.getKind().equals(itemName)){
退货项目;
}
}
返回null;
}
请给我们看一些代码。
private List<Item> items = new ArrayList<Item>() {{
add(new Item("tree", "I big green tree", 60));
add(new Item("coat", "I white coat", 5));
add(new Item("paper", "a role of wc paper", 1));
}};
public Item getItem(String itemName) {
for (Item item : this.items) {
if (item.getKind().equals(itemName)) {
return item;
}
}
return null;
}