Skip to content

Instantly share code, notes, and snippets.

@nyamwaya
Created August 10, 2016 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyamwaya/542133a672dbb5fabfcda81a13aaf217 to your computer and use it in GitHub Desktop.
Save nyamwaya/542133a672dbb5fabfcda81a13aaf217 to your computer and use it in GitHub Desktop.
/**
* Tracks the number of calories a person consumes in a given meal.
* Has helper method to get the day's total.
*/
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");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment