1
votes

I have this code (it's a java class called TshirtSearcher) that is trying to grab the t-shirt size info from a text file and put it in a enum called 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("],", ""));

This is the enum:

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";
    };
}

However, when I run the code it gives this error:

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)

Process finished with exit code 1

The file content is like this (just show the first 3 rows):

name,product code,price,brand,sizes,description

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

The Simpsons,576857394,22.99,Lacoder,[S,M,L],[Graphic text: "Worst. Episode. Ever."]


I would like the user to be able to select the size from the dropdown menu.

Thanks!

1
The error message means that you are passing the string S,M,L,XL,XXL to Size.valueOf(). That doesn't work because S,M,L,XL,XXL is not one of the enum constants. Debug your application to find out why it's passing the wrong thing to Size.valueOf(). - Jesper

1 Answers

-1
votes

On this record

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

you have a record S,M,L,XL,XXL but on your enum you haven't declered the value.

Maybe there are a error on desing.

please try to change in:

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

and try a debug test.