我有一组需要格式化的未格式化字符串。我有两个的完整列表。
这是它的一个子集:
"in room" => "ROOM"
"in big room" => "BIG ROOM"
"in building" => "BUILDING"
"in street" => "STREET"
"in house" => "STANDARD"
"Room box" => "ROOM"
"Big room box"=> "BIG ROOM"
"Street box" => "STREET"
"Box" => "STANDARD"
default value => "STANDARD"
有人告诉我使用enum
,以便我没有大量的if
,但是我不确定这会有什么帮助。我的枚举将如下所示:
public enum BoxLocation {
STANDARD("STANDARD"),
ROOM("ROOM"),
BIG_ROOM("BIG ROOM"),
...
但是我不知道如何避免大量的ifs。
我应该如何将一个或多个(默认值除外,不超过2个)未格式化的字符串绑定到格式化的字符串,最干净的方法是什么?我在想类似的东西:
if(boxLocation.equals("in room") || boxLocation.equals("Room box"))
boxLocation = BoxLocation.ROOM;
但是拥有一个枚举有什么帮助,我不能只使用它吗?
boxLocation = "ROOM";
编辑:某些格式化的值带有空格,这些空格会更改枚举。我编辑了列表。
答案 0 :(得分:2)
您可以使用类似这样的方法,假设如果在句子中的单词中包含枚举的名称,则选择枚举:
((select count(*) from comment_likes c where a.id=c.comment_id) as post_like_count FROM comment_likes a)
然后可以这样称呼它:
public enum BoxLocation {
ROOM, BUILDING, STREET, STANDARD, BIG_ROOM;
private final Pattern pattern = Pattern.compile(
name().replace('_', ' '), // take care of underscores
Pattern.CASE_INSENSITIVE
);
public static BoxLocation fromValue(String sentence) {
for (BoxLocation value : BoxLocation.values()) {
if (value.pattern.matcher(sentence).find()) {
return value;
}
}
return STANDARD;
}
}
此方法为每个枚举使用不同的BoxLocation boxLoc = BoxLocation.fromValue("In room");
(Java中用于正则表达式的类),其等效的regex如下所示:Pattern
,其中/enumname/i
是枚举,enumname
是不区分大小写的标志。
答案 1 :(得分:2)
您的枚举应如下所示:
public enum BoxLocation{
ROOM("ROOM","in room", "Room box"),
BUILDING("BUILDING","in building"),
STREET("STREET","in street", "Street box"),
STANDARD("STANDARD","in house"),
BIG_ROOM("BIG ROOM", "in big room");
private final List<String> values;
BoxLocation(String ...values) {
this.values = Arrays.asList(values);
}
public List<String> getValues() {
return values;
}
public static String find(String name) {
for (BoxLocation bl : BoxLocation.values()) {
if (bl.getValues().contains(name)) {
return bl.values.get(0);
}
}
return BoxLocation.STANDARD.values.get(0);
}
}
并使用find方法检索任何字符串的对应值
public static void main(String[] args) {
String boxLoc = BoxLocation.find("xyz");
System.out.println(boxLoc);
}
答案 2 :(得分:1)
您需要在键的顶部为Enum引入某种属性字段;像这样的东西:
public enum BoxLocation {
ROOM("in room"),
BUILDING("in building"),
...
private String definition;
BoxLocation(String definition) {
this.definition = definition;
}
}
然后,在您的代码中,您可以像
boxLocation.getDefinition().equals("in room")
Or (BoxLocation.from("in room"))
另请参见上方的汤姆(Tom's)信息和http://tutorials.jenkov.com/java/enums.html#enum-valueof,以获取更多指针
答案 3 :(得分:0)
您可以尝试将enum
的内容与String
值的String
表示形式进行比较,例如:
enum