我正在做一些事情,它根据命令和输入为您提供一个项目。如果命令是/item mythical destroyer
或/item mythical 1
(ID系统)它为您提供驱逐舰物品(任意,不用担心细节)。
考虑其他问题,它们都与枚举有关,但是我要寻找的是如何对整数和字符串进行处理。
这是我现在正在做的事情:
interface MythicalItem {
ItemStack getItem();
int getPrice();
void setPrice(int var1);
int getID();
}
class DestroyerMI implements MythicalItem {
private int price = 50;
int getID(){
return 1;
}
void setPrice(int var1){
this.price = var1;
}
int getPrice(){
return price;
}
Item getItem(){
Item item = new Item()
return item;
}
}
class MythicalUtil{
public static ItemStack parseItem(MythicalItem mythicalItem){
return mythicalItem.getItem();
}
public static int parseID(MythicalItem mythicalItem){
return mythicalItem.getID();
}
public static int parsePrice(MythicalItem mythicalItem){
return mythicalItem.getPrice();
}
}
我的问题就出现在这里,似乎没有一种方法可以通过名称/ id来获得神话般的物品,而无需巨大的开关或if / else,这是我要防止的。
// String[] args = {"mythical", "destroyer"};
if(args[0].equalsIgnoreCase("mythical")){
// I know it is supposed to be Integer.parseInt(args[1]), but dont worry about that please.
if(args[1].equals("1") || args[1].equalsIgnoreCase("destroyer")){
player.giveItem(MythicalUtil.parseItem(new DestroyerItem()));
}else if(args[1].equalsIgnoreCase("shooter"){
plaer.giveItem(MythicalUtil.parseItem(new ShooterItem()));
}else if(...
}
我想制作一种方法,可以在不使我的代码混乱的情况下将商品退还给我。
如果确实需要对Strings和Integers进行所有这些操作,并且您不想重构仅具有特定部分的所有已有代码,则可以尝试使用switch case
String appropriateNameForArg0 = args[0].toUpperCase();
String appropriateNameForArg1 = args[1].toUpperCase();
if (appropriateNameForArg0.equals("MYTHICAL")) {
switch (appropriateNameForArg1) {
case "1":
case "DESTROYER":
player.giveItem(MythicalUtil.parseItem(new DestroyerItem()));
break;
case "SHOOTER":
plaer.giveItem(MythicalUtil.parseItem(new ShooterItem()));
break;
case "...":
// some other action here
default:
// here you have a place for actions which will be triggered if appropriateNameForArg1 will not meet any of the defined cases
break;
}
}