IllegalArgumentException:没有枚举常量Java



我有一个代码(它是一个名为TshirtSearcher的java类(,试图从文本文件中获取t恤尺寸信息,并将其放入名为size:的枚举中

for (int i = 1; i < TShirtData.size(); i++) {
//split each String in the list by [ and , to separate the t-shirt name,product code,price,brand, from sizes,description
String[] elements = TShirtData.get(i).split("\[");
//separate the t-shirt info by splitting by comma. This will separate the following; name,product code,price,brand into individual items
String[] tshirtInfo = elements[0].split(",");
String name = tshirtInfo[0];
long productCode = 0;
try {
productCode = Long.parseLong(tshirtInfo[1]);
} catch (NumberFormatException n) {
System.out.println("Error in file. Product code could not be parsed for t-shirt on line " + (i + 1) + ". Terminating. nError message: " + n.getMessage());
System.exit(0);
}
//Read the data from the file as enum
Size size = Size.valueOf(elements[1].replace("],", ""));

这是枚举:

public enum Size {
XS, S, M, L, XL, XXL, XXXL, XXXXL;
/**
* @return a prettified version of the relevant enum constant
*/
public String toString() {
return switch (this) {
case XS -> "Extra Small";
case S -> "Small";
case M -> "Medium";
case L -> "Large";
case XL -> "Extra Large";
case XXL -> "2x Extra Large";
case XXXL -> "3x Extra Large";
case XXXXL -> "4x Extra Large";
};
}

然而,当我运行代码时,它会出现以下错误:

Exception in thread "main" java.lang.IllegalArgumentException: No enum constant Size.S,M,L,XL,XXL
at java.base/java.lang.Enum.valueOf(Enum.java:273)
at Size.valueOf(Size.java:6)
at TShirtSearcher.loadTShirts(TShirtSearcher.java:45)
at TShirtSearcher.main(TShirtSearcher.java:121)

进程结束,退出代码为1

文件内容如下(只显示前3行(:

名称、产品代码、价格、品牌、尺寸、描述

你好世界,852760540,34.96,Tommy Bugfinder,[S,M,L,XL,XXL],[图文:"你好世界"]

《辛普森一家》,576857394,22.99,拉科德,[S,M,L],[图文:"史上最糟糕的一集。"]


我希望用户能够从下拉菜单中选择尺寸。

谢谢!

感谢@Jesper和@Davide:-(我通过创建一个拆分元素列表解决了这个问题:

String[] sizeSplit = elements[1].split(",");
Size size = Size.valueOf(sizeSplit[1]);

在此记录上

hello world,852760540,34.96,Tommy Bugfinder,[S,M,L,XL,XXL],[Graphic text: "Hello world"]

你有一个记录S,M,L,XL,XXL,但在你的枚举中,你还没有清除值。

也许设计上有错误。

请尝试更改:

hello world,852760540,34.96,Tommy Bugfinder,[S],[Graphic text: "Hello world"]

并尝试调试测试。

最新更新