Tracks the number of calories a person consumes in a given meal it has helper method to get the day's total. The check method Tries to find any duplicate meals within the given list. The assumption is that a day can only contain one of each type of meal.
public class Meal {
public enum Type {
BREAKFAST,
LUNCH,
DINER,
}
public Type type;
double caloriesConsumed;
public Meal(Type type, double caloriesConsumed) {
this.type = type;
this.caloriesConsumed = caloriesConsumed;
}
//Gets calories burned
public double getCaloriesConsumed() {
return caloriesConsumed;
}
//Sets calories burned
public void setCaloriesConsumed(double caloriesConsumed) {
this.caloriesConsumed = caloriesConsumed;
}
//Get type
public Type getType() {
return type;
}
//Set type
public void setType(Type type) {
this.type = type;
}
public boolean equals(Meal meal) {
return meal.getType() == meal.getType() && meal.getCaloriesConsumed() == getCaloriesConsumed();
}
public static void check(Meal... meals) throws Exception {
/**
* Tries to find any duplicate meals within the given list.
* The assumption is that a day can only contain one of each type of meal.
*/
ArrayList<Type> types = new ArrayList<Type>();
for (int i = 0; i < meals.length; i++) {
if (types.contains(meals[i].type))
{
throw new Exception();
}
else
{
types.add(meals[i].type);
}
}
}
public static double getTodaysCalories(Meal... meals) throws Exception
{
check(meals);
double total = 0;
for (Meal meal : meals) {
total += meal.caloriesConsumed; //Add calories to total
}
return total;
}
public static void main(String[] args) {
Meal breakfast = new Meal(Type.BREAKFAST, 500.7);
Meal lunch = new Meal(Type.LUNCH, 378.9);
Meal dinner = new Meal(Type.DINER, 620.1);
try {
double caloriesConsumed = Meal.getTodaysCalories(breakfast, lunch, dinner);
System.out.println("Today's Total Calories is " + caloriesConsumed);
} catch (Exception e) {
System.out.println("Unable to calculate today's calories");
}
}
}
fix issues
, do you have issues in your code ? And please edit the title of the question to describe what your code is doing, not what you want as a review. \$\endgroup\${}
or Ctrl + K. I had to edit it again. And please do edit your title to a short description of what your progam do. \$\endgroup\$