我有一個關於使用下面的枚舉文件提供給我的最佳方法的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