我有一个关于使用下面的枚举文件提供给我的最佳方法的Java问题。Java枚举处理
public enum Foo{
PLANE(1, "Plane", "plane"),
CASTLE(2, "Castle", "castle"),
FEILD(3, "Feild", "field"),
ROAD(4, "Road", new String[] {"road", "pavement"});
}
有上述格式大致100ish项
/**
* Stores a map of the names for fast access. Stores a map of the IDs for fast access.
*/
private static final Map<Integer,BlockType> ids = new HashMap<Integer,BlockType>();
private static final Map<String,BlockType> lookup = new HashMap<String,BlockType>();
private final int id;
private final String name;
private final String[] lookupKeys;
static {
for(Foo type : EnumSet.allOf(Foo.class)) {
ids.put(type.id, type);
for (String key : type.lookupKeys) {
lookup.put(key, type);
}
}
}
/**
* Construct the type.
*
* @param id
* @param name
*/
Foo(int id, String name, String lookupKey) {
this.id = id;
this.name = name;
this.lookupKeys = new String[]{lookupKey};
}
/**
* Construct the type.
*
* @param id
* @param name
*/
Foo(int id, String name, String[] lookupKeys) {
this.id = id;
this.name = name;
this.lookupKeys = lookupKeys;
}
/**
* Return type from ID. May return null.
*
* @param id
* @return
*/
public static Foo fromID(int id) {
return ids.get(id);
}
/**
* Return type from name. May return null.
*
* @param name
* @return
*/
public static Foo lookup(String name) {
return lookup.get(name.toLowerCase());
}
/**
* Get block numeric ID.
*
* @return
*/
public int getID() {
return id;
}
/**
* Get user-friendly name.
*
* @return
*/
public String getName() {
return name;
}
那么我想这个枚举做的是以下几点: 用户发出命令,例如:/反弹1
程序将弹跳识别为命令并查找以下参数。由于1遵循命令,它现在检查1是枚举中的有效id#。如果它是执行命令。
用户以下面的形式发出示例2的命令:/弹跳平面。这一次它会检查该字符串是否在枚举中是一个有效的字符串名称,如果它是获取与其关联的id#以执行该命令。
如何检查这些标准是否存在id或其中一个字符串id,并始终返回id#以供以后使用。任何帮助,将不胜感激。
还应该注意的是,这个枚举文件是它自己的独立类文件被从main调用。
感谢所有帮助我走上正轨的人,我已经授予沃尔夫卡斯尔正确的答案,这里是我为我工作的东西,但我仍然乐于接受任何有关我的方法对逻辑或性能缺陷的批评。
String s = null;
try {
s = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
id = Integer.parseInt(s);
} catch (NumberFormatException nfe) {
}
if (BlockType.lookup(s) != null
|| BlockType.fromID(id) != null) {
if (BlockType.lookup(s)!= null) {
blockname = BlockType.lookup(s).getName();
blockid = BlockType.lookup(s).getID();
} else {
blockname = BlockType.fromID(id).getName();
blockid = BlockType.fromID(id).getID();
}
}
我不清楚你的问题是什么。你的代码看起来应该做你想做的事情。你可以扩展你遇到的实际问题吗? – wolfcastle 2011-04-20 19:07:02
这是通过合作团队提供给我的制作插件的文件。我的包在这个文件中使用enum来验证用户试图创建的“item”实际上是否通过项目ID#或它的字符串名称存在于枚举中。如果用户使用字符串名称发送命令,则需要根据字符串名称获取项目标识,以便可以创建该项目。 (希望这更有意义) – JDD 2011-04-20 20:36:43
'BlockType'与'Foo'相同吗? – 2011-04-20 21:13:09