Код: Выделить всё
package Main;
import java.util.ArrayList;
import java.util.List;
public class Main {
List 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) {
int totalCost = size.getCost();
for (Ingredients ingredient : ingredients) {
totalCost += ingredient.getCost();
}
return totalCost;
}
public static void main(String[] args) {
List 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, поэтому не действительно много знаю о перечислениях, поэтому смогу узнать о них больше позже
Подробнее здесь: https://stackoverflow.com/questions/785 ... -of-coffee
Мобильная версия