Home > database >  Constant expression required in switch statements
Constant expression required in switch statements

Time:01-17

have this enum file containing some information:

public enum Constants {
    AGED_BRIE("Aged Brie");

    private final String label;

    Constants(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}

this Item class:

public class Item {
    public String name;

    public Item(String name) {
        this.name = name;
    }
}

and this factory method:

public class Factory {

    public void try(Item item) {
        String brie = Constants.AGED_BRIE.getLabel(); // contains "Aged Brie"
        switch (item.name) {
            case brie -> System.out.println("Hello World"); // Constant expression required
            // other cases ...
        }
    }
}

Unfortunately I get:

Constant expression required

and IntelliJ highlights case label statement.

  • What am I missing?

CodePudding user response:

You can't have a method named try. You need your case(s) to expand to constants. You shouldn't make fields public. But let's start by making Constants into Cheese. Like,

public enum Cheese {
    CHEDDAR("Cheddar"), AGED_BRIE("Aged Brie");

    private final String label;

    Cheese(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}

Now in Item, instead of String(s) we want to use the enum type so you have something to match on in constant expressions later. Not changing Constants would have made this confusing. Like,

public class Item {
    private Cheese cheese;

    public Item(Cheese cheese) {
        this.cheese = cheese;
    }

    public Cheese getCheese() {
        return cheese;
    }
}

Now, we can actually use that for our case(s). It's a Factory. We can make things. Like,

public void make(Item item) {
    switch (item.getCheese()) {
    case AGED_BRIE -> System.out.println("Aged Brie");
    case CHEDDAR -> System.out.println("Cheddar");
    }
}

CodePudding user response:

you cannot declare a case with -> , you have to use ":". And don't forget to add break; after each case.

case brie:
            System.out.println("Hello World");
            break;

case example:
            System.out.println("exemple");
            break;
  • Related