如何正确使用枚举来进行简单的价格计算(Java)

发布于 2025-01-31 10:44:39 字数 4075 浏览 0 评论 0原文

我正在尝试优化一个看起来像这样的代码刺:

public class Kvarteret {
    public static final String ONE_BEER = "hansa";
    public static final String ONE_CIDER = "grans";
    public static final String REAL_BEER = "vestkyst";
    public static final String GT = "gt";
    public static final String BACARDI_SPECIAL = "bacardi_special";

    public int calculatePrice(String drink, boolean student, int amount) {

        if (amount > 2 && (drink == GT || drink == BACARDI_SPECIAL)) {
            throw new RuntimeException("Too many drinks, max 2.");
        }

        int price;

        if (drink.equals(ONE_BEER)) { price = 74;}
        else if (drink.equals(ONE_CIDER)) { price = 103;}
        else if (drink.equals(REAL_BEER)) { price = 110; }
        else if (drink.equals(GT)) { price = ingredient6() + ingredient5() + ingredient4();}
        else if (drink.equals(BACARDI_SPECIAL)) {
            price = ingredient6()/2 + ingredient1() + ingredient2() + ingredient3();
        } else { throw new RuntimeException("Item not in menu"); }

        if (student && (drink == ONE_BEER || drink == ONE_CIDER || drink == REAL_BEER)) { price = price - price/10;}
        return price*amount;
    }

    //rom unit
    private int ingredient1() { return 65;}

    // grenadine unit
    private int ingredient2() { return 10;}

    //lime-juice unit
    private int ingredient3() { return 10;}

    //mint-leafs unit
    private int ingredient4() { return 10; }

    //tonic-water unit
    private int ingredient5() { return 20; }

    //gin unit
    private int ingredient6() { return 85; }
}

代码是一个简单的程序,可以计算饮料的价格。我使用代码作为起点,因为他们似乎我们正在尝试做类似的事情。

到目前为止,我的代码看起来像这样:

import java.util.*;

public class Kvarteret2 {
    private static double price;
    private static double order;

    // Enums defines common values
    private enum Beer_Cider {
        BEER("Hansa", 74), CIDER("Grans", 103), REAL_BEER("Vestkyst", 110);

        private static String order;

        Beer_Cider(String order, double cost) {
            order = order;
            price = cost;
        }

        private static String getOrder() {return order;}
        private static double getCost() {return price;}
    }

    private enum DrinkIngredients {

        ROM("Rom", 65), GRENADINE("Grenadine", 10), LIME("Lime-juice", 10),
        MINT("Mint", 10), TONIC("Tonic-water", 20), GIN("Gin", 85);

        private static String ingredient;

        DrinkIngredients(String ingredient, double cost){
            ingredient = ingredient;
            price = cost;
        }

        private static String getIngredient() {return ingredient;}
        private static double getCost() {return price;}
    }

    // Dictionary with the drink as Key and a list of the ingredients and prices as value
    Map<String, List<DrinkIngredients>> Drinks = new HashMap<String, List<DrinkIngredients>>(); 

    public Kvarteret2() {
        Drinks.put("GT", [DrinkIngredients.GIN, DrinkIngredients.TONIC, DrinkIngredients.MINT]);

    }


    private static double calculate_price(String drink, boolean student, int amount){

        if (amount > 2) {
            throw new IllegalArgumentException("Too many drinks! You can order max 2 drinks at a time.");
        }

        double student_discount = 0.1;

        if (student){
            if (drink == "BEER" || drink == "CIDER" || drink == "REAL BEER") {
                price = amount * (price - price * student_discount);
            }
        }
        return price;
    }
}

由于此代码,我会遇到错误:

public Kvarteret2() {
    Drinks.put("GT", [DrinkIngredients.GIN, DrinkIngredients.TONIC, DrinkIngredients.MINT]);

}

我正在尝试将元素添加到字典中,但我认为这不是正确的方法。

我知道我的代码可能还没有100%优化,但是我只想在尝试使其变得更好之前是否可以使该解决方案起作用(因为很可能有更好的方法可以做到这一点)。

如何正确创建要使用枚举创建的字典?

I am trying to optimize a code-snippet that looks like this:

public class Kvarteret {
    public static final String ONE_BEER = "hansa";
    public static final String ONE_CIDER = "grans";
    public static final String REAL_BEER = "vestkyst";
    public static final String GT = "gt";
    public static final String BACARDI_SPECIAL = "bacardi_special";

    public int calculatePrice(String drink, boolean student, int amount) {

        if (amount > 2 && (drink == GT || drink == BACARDI_SPECIAL)) {
            throw new RuntimeException("Too many drinks, max 2.");
        }

        int price;

        if (drink.equals(ONE_BEER)) { price = 74;}
        else if (drink.equals(ONE_CIDER)) { price = 103;}
        else if (drink.equals(REAL_BEER)) { price = 110; }
        else if (drink.equals(GT)) { price = ingredient6() + ingredient5() + ingredient4();}
        else if (drink.equals(BACARDI_SPECIAL)) {
            price = ingredient6()/2 + ingredient1() + ingredient2() + ingredient3();
        } else { throw new RuntimeException("Item not in menu"); }

        if (student && (drink == ONE_BEER || drink == ONE_CIDER || drink == REAL_BEER)) { price = price - price/10;}
        return price*amount;
    }

    //rom unit
    private int ingredient1() { return 65;}

    // grenadine unit
    private int ingredient2() { return 10;}

    //lime-juice unit
    private int ingredient3() { return 10;}

    //mint-leafs unit
    private int ingredient4() { return 10; }

    //tonic-water unit
    private int ingredient5() { return 20; }

    //gin unit
    private int ingredient6() { return 85; }
}

The code is a simple program that calculates the price of drinks. I used this code as a starting point because it seemed like they we're trying to do something similar.

My code so far looks like this:

import java.util.*;

public class Kvarteret2 {
    private static double price;
    private static double order;

    // Enums defines common values
    private enum Beer_Cider {
        BEER("Hansa", 74), CIDER("Grans", 103), REAL_BEER("Vestkyst", 110);

        private static String order;

        Beer_Cider(String order, double cost) {
            order = order;
            price = cost;
        }

        private static String getOrder() {return order;}
        private static double getCost() {return price;}
    }

    private enum DrinkIngredients {

        ROM("Rom", 65), GRENADINE("Grenadine", 10), LIME("Lime-juice", 10),
        MINT("Mint", 10), TONIC("Tonic-water", 20), GIN("Gin", 85);

        private static String ingredient;

        DrinkIngredients(String ingredient, double cost){
            ingredient = ingredient;
            price = cost;
        }

        private static String getIngredient() {return ingredient;}
        private static double getCost() {return price;}
    }

    // Dictionary with the drink as Key and a list of the ingredients and prices as value
    Map<String, List<DrinkIngredients>> Drinks = new HashMap<String, List<DrinkIngredients>>(); 

    public Kvarteret2() {
        Drinks.put("GT", [DrinkIngredients.GIN, DrinkIngredients.TONIC, DrinkIngredients.MINT]);

    }


    private static double calculate_price(String drink, boolean student, int amount){

        if (amount > 2) {
            throw new IllegalArgumentException("Too many drinks! You can order max 2 drinks at a time.");
        }

        double student_discount = 0.1;

        if (student){
            if (drink == "BEER" || drink == "CIDER" || drink == "REAL BEER") {
                price = amount * (price - price * student_discount);
            }
        }
        return price;
    }
}

I'm getting an error because of this code:

public Kvarteret2() {
    Drinks.put("GT", [DrinkIngredients.GIN, DrinkIngredients.TONIC, DrinkIngredients.MINT]);

}

I am trying to add elements to the dictionary, but I dont think this is the right way to do it.

I know my code might not be 100% optimized yet, but I just want to see if I can make this solution work before I try to make it even better (because there's most likely a better way to do this).

How do I properly create the dictionary I am trying to create using the enums?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

新一帅帅 2025-02-07 10:44:39

您的代码中有很多错误。

您正在使用错误的语法来创建Java中的A list 它的工作方式与JavaScript )的

[DrinkIngredients.GIN, DrinkIngredients.TONIC, DrinkIngredients.MINT] // <- that's not correct

List.of(DrinkIngredients.GIN, DrinkIngredients.TONIC, DrinkIngredients.MINT) // <- correct

工作方式相同 。特定的枚举恒定不应标记静态。修改器static表明在类的所有实例中共享一个字段,enum在一天结束时是类。如果您想要字符串order在各种饮料中都是唯一的,则该行不正确:

private static String order;

构造函数中的另一个错误:

Beer_Cider(String order, double cost) {
    order = order;
    price = cost;
}

line order = order = order = order; 在您时行不通预计。它不会将对象属性分配,而只是将参数重新分配给本身。您应该使用关键字 参考对象字段顺序。

private enum BeerCider {
    BEER("Hansa", 74), CIDER("Grans", 103), REAL_BEER("Vestkyst", 110);
    
    private String order;
    private double cost;
    
    Beer_Cider(String order, double cost) {
        this.order = order;
        this.cost = cost;
    }
    
    private String getOrder() {return order;}
    private double getCost() {return cost;}
}

有关 enums 的更多信息,请查看 此教程

sidenote:根据 /code>字段),但是enum的名称必须用骆驼盒beercider,例如类和接口的名称。

There are a lot of mistakes in your code.

You are using an incorrect syntax for creating a list in Java (it doesn't work in the same way as in JavaScript):

[DrinkIngredients.GIN, DrinkIngredients.TONIC, DrinkIngredients.MINT] // <- that's not correct

List.of(DrinkIngredients.GIN, DrinkIngredients.TONIC, DrinkIngredients.MINT) // <- correct

Enum-fields that has to be associated with a specific enum-constant should not be marked static. Modifier static indicates that a field is shared among all the instances of a class, enums at the end of the day are classes. If you want string order to be unique for all kinds of drinks, this line is not correct:

private static String order;

Another mistake in the constructor:

Beer_Cider(String order, double cost) {
    order = order;
    price = cost;
}

Line order = order; will not work as you expect. It will not assign the object property, instead it just reassigns parameter order to itself. You should use the keyword this to refer to the object field order.

private enum BeerCider {
    BEER("Hansa", 74), CIDER("Grans", 103), REAL_BEER("Vestkyst", 110);
    
    private String order;
    private double cost;
    
    Beer_Cider(String order, double cost) {
        this.order = order;
        this.cost = cost;
    }
    
    private String getOrder() {return order;}
    private double getCost() {return cost;}
}

For more information of enums have a look at this tutorial

Sidenote: according to Java naming conventions underscore should be used only the names of constants (like unum-members, static final fields), but the name of an enum has to be written in camel-case BeerCider, like names of classes and interfaces.

囚我心虐我身 2025-02-07 10:44:39

尽管您尚未提及您遇到的错误,但这就是您可以填充kvarteret2构造函数的方式:

// Dictionary with the drink as Key and a list of the ingredients and prices as value
    Map<String, List<DrinkIngredients>> Drinks = new HashMap<String, List<DrinkIngredients>>(); 
   List<DrinkIngredients> list=new ArrayList<DrinkIngredients>(); // define ArrayList outside constructor

public Kvarteret2() {
  list.add(DrinkIngredients.GIN);
  list.add(DrinkIngredients.TONIC);
  list.add(DrinkIngredients.MINT);
  Drinks.put("GT", ls);
}

Though you haven't mentioned what error you got, but this is how you can populate your Kvarteret2 constructor:

// Dictionary with the drink as Key and a list of the ingredients and prices as value
    Map<String, List<DrinkIngredients>> Drinks = new HashMap<String, List<DrinkIngredients>>(); 
   List<DrinkIngredients> list=new ArrayList<DrinkIngredients>(); // define ArrayList outside constructor

public Kvarteret2() {
  list.add(DrinkIngredients.GIN);
  list.add(DrinkIngredients.TONIC);
  list.add(DrinkIngredients.MINT);
  Drinks.put("GT", ls);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文