访问枚举 variables/methods

Accessing enum variables/methods

enum ChineseMenu {

    SOUP_CHICKEN(22), SOUP_VEG(32),

    NOODLES_NONVEG(23), NOODLES_VEG(55),

    RICE_NONVEG(43), RICE_VEG(66);

    private int value;

    ChineseMenu(int price) {
        this.value = price;
    }

    public int getCost() {
        return value;
    }
}




class ChineseDemo {

    public static void main(String[] args) {
        ChineseMenu[] chineseArray = ChineseMenu.values();
        for (ChineseMenu menu : chineseArray) {
            System.out.println("The price of " + menu + " is ");//i want to add the price value
        }

    }
}

在上面的代码中,我想在 "is" 之后添加价格值。我什至尝试声明一个方法然后调用它。但是报错static type cannot reference non static variables

这个怎么样:

System.out.println("The price of " + menu + " is " + menu.getCost());

In the above code i want to add the prices value after "is"

从你的问题上面这行判断,以及你的打印语句显示 The price of menu is,看起来你想打印中文菜单的总费用:

您可以创建一个名为 total 的变量来保存总价:

public static void main(String[] args) {
        ChineseMenu[] chineseArray = ChineseMenu.values();
        int total = 0;
        for (ChineseMenu menu : chineseArray) {
            total+=menu.getCost();

        }
        System.out.println("The price of Chinese menu is "+total);

}