gpt4 book ai didi

java - 在 Java 中使用枚举代替 switch

转载 作者:行者123 更新时间:2023-12-02 03:55:42 24 4
gpt4 key购买 nike

我使用枚举而不是开关,但有一个问题。在 switch 中,您可以有一个默认情况。但是使用枚举又如何呢?当我提供的输入与定义的枚举不同时,我的程序崩溃了。

例如:

public enum InputChar {

X,Y,Z;

/**
* get an input character
* @return a String description of the input character
*/

@Override
public String toString()
{
String s = "";
if (this.ordinal() == 0)
s = "X";
else if (this.ordinal() == 1)
s = "Y";
else if (this.ordinal() == 2)
s = "Z";

return s;
}
}

我正在使用它:

private void checkInput(String charEntered) 
{
textDoc = new textDoc (InputChar.valueOf(charEntered));
}

我已经研究过了,但无法让它发挥作用。考虑过在 toString() 中添加 else 语句,但似乎无法在其中添加 default ...

最佳答案

有两件事:

  1. 默认情况下,枚举有一个默认实现,它仅返回其 .name();因此你在这里的覆盖是多余的;
  2. 枚举是“像其他任何类一样”(几乎如此)的类,因此它们有构造函数;如果你想将数据“添加”到枚举中,正确的方法如下:
<小时/>
public enum MyEnum
{
FOO("my data"),
;

private final String whatever;

MyEnum(final String whatever)
{
this.whatever = whatever;
}

public String getWhatever()
{
return whatever;
}
}

关于java - 在 Java 中使用枚举代替 switch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35484616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com