use方法在主类中被调用,该类称为Game。
public class Player
{
public String playerName;
public int carryWeight;
public int carryWeightLimit;
ArrayList<Item> heldItems;
public Player()
{
heldItems = new ArrayList<Item>();
playerName = " ";
carryWeight = 0;
carryWeightLimit = 10;
}
//some parts omitted
public void useItem()
{
ITEMS item =
// The above line is what I'm having problems with completing.
switch (item) {
case TOY:
useToy();
break;
case TREATS:
useTreats();
break;
case LEASH:
useLeash();
break;
case KEY:
useKey();
break;
}
return;
}
Game
类传递它。那么你可以像这样转变你的使用方法:
public void useItem(ITEMS item)
据我了解 ITEMS
是一个枚举,然后
Game
类将从控制台读取 String,将其映射到枚举并传递给
Player
类。让我们从映射开始:
enum ITEMS {
TOY, TREATS, LEASH, KEY;
public static ITEMS findByName(String name) {
ITEMS result = null;
for (ITEMS item : values()) {
if (item.name().equalsIgnoreCase(name)) {
result = item;
break;
}
}
return result;
}
}
然后读取输入,要求枚举将 String
映射到
ITEMS
并将其传递给
Player.useItem()
:
String itemString = // read user item input from console.
ITEMS item = ITEMS.findByName(itemString);
Player player = new Player();
player.useItem(item);