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));
}
我期待一个带有数字的浮点数
6.5
这是输出
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)
它说这是一个问题
totalCost += ingredient.getCost();
但这并不是问题,直到我将枚举成分设为浮点数
我对 Java 编码相当陌生,所以我对枚举不太了解,所以我稍后可能会了解更多关于它们的信息
以下是更正后的类型。
public class CoffeOrder {
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 double cost;
Ingredients(double cost) {
this.cost = cost;
}
public double getCost() {
return cost;
}
}
public enum Sizes {
SMALL(5),
MEDIUM(10),
LARGE(15);
private final int cost;
Sizes(double cost) {
this.cost = cost;
}
public double getCost() {
return cost;
}
}
public static double calculateCost(Sizes size, List<Ingredients> ingredients) {
double 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));
}
}
打印
Cost of a small size coffee with milk and suger: 6.5