package Main;
import java.util.ArrayList;
import java.util.List;
public class Main {
List<Ingredients> ingredients = new ArrayList<>();
public enum Ingredients {
SUGAR(0.25), // these are the problem
MILK(1.25), // this
CREAM(1.75); // and this one
private final float cost;
Ingredients(int cost) {
this.cost = cost;
}
public float getCost() {
return cost;
}
}
public enum Sizes {
SMALL(5),
MEDIUM(10),
LARGE(15);
private final int cost;
Sizes(int cost) {
this.cost = cost;
}
public int getCost() {
return cost;
}
}
public static float calculateCost(Sizes size, List<Ingredients> ingredients) {
int totalCost = size.getCost();
for (Ingredients ingredient : ingredients) {
totalCost += ingredient.getCost();
}
return totalCost;
}
public static void main(String[] args) {
List<Ingredients> ingredients = new ArrayList<>();
ingredients.add(Ingredients.MILK);
ingredients.add(Ingredients.SUGAR);
System.out.println("Cost of a small size coffee with milk and suger: " + calculateCost(Sizes.SMALL, ingredients));
}
i was expecting a float with the number
6.5
this was the output
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Main.Main$Ingredients.getCost()" because "ingredient" is null
at Java/Main.Main.calculateCost(Main.java:44)
at Java/Main.Main.main(Main.java:53)
it says that this is a problem
totalCost += ingredient.getCost();
but is was not a problem earlier until i made the enum ingredients a float
i am fairly new to coding in java so i don’t really know much about enums so i might learn more about them later