java中按字符串切换大小写<;1.7
我知道按字符串大小写的开关仅在>1.7时可用。我是否可以在java中转换这段代码,而不用使用传统的java中按字符串切换大小写<;1.7,java,javascript,switch-statement,Java,Javascript,Switch Statement,我知道按字符串大小写的开关仅在>1.7时可用。我是否可以在java中转换这段代码,而不用使用传统的if/else。这段代码是用JavaScript编写的,请改用enum,因为您可以使用enum进行如下操作: private enum MyEnum { a, b, c, d; } String val; // input MyEnum mye = MyEnum.valueOf(val); switch (mye) { ca
if/else
。这段代码是用JavaScript
编写的,请改用enum,因为您可以使用enum进行如下操作:
private enum MyEnum {
a, b, c, d;
}
String val; // input
MyEnum mye = MyEnum.valueOf(val);
switch (mye) {
case a:
return something;
case carrot:
return something;
..
}
如果您认为try块太难看,您可以使用from,这将为您提供帮助,您只需更改以下内容:
enum MyEnum {
A1, A2, A3;
}
String val = "myVal"; // your input
MyEnum enumVal;
try {
enumVal = MyEnum(val);
} catch (IllegalArgumentException iae) {
enumVal = null;
}
switch (enumVal) {
case A1:
doSomething();
break;
case A2:
doOtherStuff();
break;
default:
doDefault();
break;
}
为此:
MyEnum enumVal;
try {
enumVal = MyEnum(val);
} catch (IllegalArgumentException iae) {
enumVal = null;
}
编辑
对于只过滤非字符串的布尔值的情况,可以执行以下操作:
MyEnum enumVal = EnumUtils.getEnum(MyEnum.class, val);
如果它们是字符串,则需要比较字符串本身,如:
Object input = "MyString";
if (input == Boolean.TRUE) {
return "Yes";
} else if (input == Boolean.FALSE) {
return "No";
} else {
return input;
}
我更喜欢if/else,但是你可以创建和使用enum。你可以使用enum来做开关,将字符串表示为enumsCan我们在enum private enum MyEnum{true,false}中没有布尔值。你需要它来表示true/false吗?在这种情况下,使用
if
语句和Boolean.parseBoolean(String value)
更容易(因此它们确实是这样),当String
为时,它将返回true
。等于到“true”
或false
。是的,我需要它来表示真/假。。。我从服务中获得的信息为真或假,我需要在前端显示“是”或“否”,事实上,“真”
和“假”
不能用作枚举的有效值,但java枚举应该是大写的,意思是真
和假
,这是允许的,但在执行valueOf()之前,需要将字符串上移(如果要使用枚举方法)感谢您的详细回答为了涵盖default
案例,您可以在try-catch中执行valueOf,在异常时为其分配null
,或者使用apache commons中的EnumUtils
,在不引发异常的情况下获取枚举值,然后执行切换案例JavaScript代码不仅仅是开关的情况(类型检查、隐式类型转换等)。switch case本身只使用布尔条件,也可以在Java中实现,而不使用枚举。@JavaMentor您是对的。但是我非常抱歉没有提供完整的代码,因为我无法提供。
Object input = "MyString";
if (input == Boolean.TRUE) {
return "Yes";
} else if (input == Boolean.FALSE) {
return "No";
} else {
return input;
}
if ("true".equals(input)) {
return "Yes";
} else if ("false".equals(input)) {
return "No";
} else {
return input;
}