我第一次尝试使用枚举。 对于某些测试,我想覆盖我的枚举的toString方法,并返回带有所选枚举的String。
到目前为止,这里有我的代码:
@Override
public String toString()
{
return "Fahrzeuge{" +
switch(this)
{
case MOTORAD: "1"; break;
case LKW: "2"; break;
case PKW: "3"; break;
case FAHRRAD: "4"; break;
}
+
"typ:" + this.typ +
", ps:" + this.ps +
", reifen:" + this.reifen +
", gewicht:" + this.gewicht +
"}";
}
IntelliJ强调了我的情况,并告诉我以下内容:“不是声明” =>我想这是有道理的,如果不允许使用switch-case来构建String。
到目前为止,还不错,但是返回通过开关盒构建的String似乎是不可能的,或者我返回时是否犯了一个错误? 还有其他选项可以返回所选的枚举吗? 我可以添加一个保存我选择的枚举名称的属性,但是我可以简化一点。
感谢帮助
答案 0 :(得分:1)
可以按照JEP 325返回从Java 12开始的switch
语句的值。检查您的Java版本,如果它的版本小于12,则无法使用switch
,因此必须首先将预期值保存在局部变量中。我的意思是,如果您的Java版本早于12,则必须执行以下操作:
String num = "";
switch (this)
{
case MOTORAD:
num = "1";
break;
case LKW:
num = "2";
break;
case PKW:
num = "3";
break;
case FAHRRAD:
num = "4";
break;
}
return "Fahrzeuge{" + num +
"typ:" + this.typ +
", ps:" + this.ps +
", reifen:" + this.reifen +
", gewicht:" + this.gewicht +
"}";
但是,如果您安装了Java 12(或更高版本),则可以执行此操作(请注意不同的语法!):
return "Fahrzeuge{" +
switch (this)
{
case MOTORAD -> "1";
case LKW -> "2";
case PKW -> "3";
case FAHRRAD -> "4";
}
+ "typ:" + this.typ +
", ps:" + this.ps +
", reifen:" + this.reifen +
", gewicht:" + this.gewicht +
"}";
和 do 注意,如果数字与声明枚举值的顺序相对应,则可以简单地使用ordinal()
:
return "Fahrzeuge{" + this.ordinal() +
"typ:" + this.typ +
", ps:" + this.ps +
", reifen:" + this.reifen +
", gewicht:" + this.gewicht +
"}";
答案 1 :(得分:0)
我认为您真的不需要switch语句,因为枚举的超类已经知道您的“类型”的名称:
@Override
public String toString()
{
return "Fahrzeuge: " + super.toString() +
", ps:" + this.ps +
", reifen:" + this.reifen +
", gewicht:" + this.gewicht;
}
只需调用超类的toString()方法,即可获取当前所选枚举类型的字符串值。您甚至可以删除类型字符串。