簡體   English   中英

switch 語句中需要常量表達式

[英]Constant expression required in switch statements

讓這個enum文件包含一些信息:

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

    private final String label;

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

    public String getLabel() {
        return label;
    }
}

Item class:

public class Item {
    public String name;

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

這個工廠方法:

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 ...
        }
    }
}

不幸的是我得到:

需要常量表達式

IntelliJ 突出顯示case label語句。

  • 我錯過了什么?

你不能有一個名為try的方法。 您需要將案例擴展為常量。 您不應該公開字段。 但是,讓我們從將Constants變成Cheese開始吧。 喜歡,

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

    private final String label;

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

    public String getLabel() {
        return label;
    }
}

現在在Item中,我們想使用enum類型而不是String (s),這樣您稍后就可以在常量表達式中匹配一些東西。 不改變Constants會使這變得混亂。 喜歡,

public class Item {
    private Cheese cheese;

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

    public Cheese getCheese() {
        return cheese;
    }
}

現在,我們實際上可以將其用於我們的case 這是一個Factory 我們可以make東西。 喜歡,

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

你不能用 -> 聲明一個案例,你必須使用“:”。 並且不要忘記添加中斷; 在每個案例之后。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM