Home > Software engineering >  How to properly use enums for simple price calculation (Java)
How to properly use enums for simple price calculation (Java)

Time:05-24

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 get 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 dicitonary I am trying to create using the enums? All help is appreciated!

CodePudding user response:

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.

CodePudding user response:

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);
}
  • Related