Great Deal! Get Instant $10 FREE in Account on First Order + 10% Cashback on Every Order Order Now

COMP 1020 Lab 2 MATERIAL COVERED • More advanced Objects. • Method structure and code design • Working with existing code • Arrays Notes: • These exercises are intended to give you basic practice in...

1 answer below »
COMP 1020
Lab 2

MATERIAL COVERED


• More advanced Objects.
• Method structure and code design
• Working with existing code
• A
ays

Notes:
• These exercises are intended to give you basic practice in using Java (as opposed to Processing or Python).
• You should definitely do at least the Bronze and Silver exercises. You can do these
o before the lab, on your own, using any Java programming environment you like, or
o during the lab, with assistance from the lab TA, or
o after the lab, on your own.
• For credit, you must demonstrate at least one working exercise (Bronze), in the lab.
• Make sure your TA has recorded your mark before leaving.
• The three questions are sequential – each builds on the previous one.
• Always try to complete as many exercises as you can on every lab. Everyone should try to complete at least the
Bronze and Silver exercises while Gold will push your skills and help you study the material in more detail.

Bronze:

Continuing from where we left off last week, our next we will upgrade the VendingMachine class. We are going to extend it
so we can create and use VendingMachine objects. This is a more intuitive structure since we can imagine our
VendingMachine being a physical object that would contain some set of Foods. It will also allow us to create multiple
vending machines, each with their own a
ay of Food.
Since our main method is static, and static means not instance, we will then need to create at least one instance of our
VendingMachine object in order to access the instance methods that we will create.
While I have typically been separating the functionality into different classes to avoid confusion, there is nothing wrong with
having VendingMachine being both an Object class with instance methods and variables, while also containing static
methods (such as main) that can create new VendingMachine objects for testing.
Add the following variables to your VendingMachine class
• An instance variable that is an a
ay of Food objects.
• A static int variable with a value of 10. This will be our max a
ay size for all our vending machines and will be
used in the VendingMachine constructor to specify the a
ay size. Since it is static all instances will share it. If we
want to change the size of all the a
ays in all machines, you just change this value.
• You should then add a constructor to the VendingMachine class that simply creates a new a
ay of the specified
size.
Once you have that in place, complete the toString, size, addFood and countFood methods as outlined in their
comment blocks. When you are done that, you should be able to run the test method provided and get the same output as
the example.
Tip: The a
ay is used differently in this class then the assignment. For the lab, the a
ay will contain several null
entries and new Food objects will be added to a specific index instead of in order. You have to be extra careful with
this usage to always check if the value in the a
ay is null before calling it.
Silver:
Next, we will add nutritional information to our Ingredients class. Add 4 new instance variables of type double: ca
s,
fat, protein and servingSize. These will store information about our Ingredients nutritional information. All are in
Grams (make a note in your comments) and the nutritional information is defined in terms of grams per serving, so will need
to be converted to the co
ect values based on the amount actually used.
Add another constructor to Ingredients that includes parameters for each value.
Add the following methods to Ingredients:
Proportion of a serving this Ingredient contains as defined by (amount / servingSize)

Returns the proportion of a serving size this Ingredient represents, or 0 if it is undefined. (It should not crash if the
old version of the constructor is used and the nutritional information is not set.
Eg. If you have a serving size of 60g, and you have an amount of 30g, your proportion would be .5.
public double getProportion()

Calculate calories per serving for this Ingredient.
Protein has 4 calories per g, fat has 9 calories per g, ca
s have 4 calories per g as well.
public double getCaloriesPerServing()

Total calories for the amount of food defined in this object. That is, find the calories per serving and the amount of
servings you have and calculate the total calories from that. You should be able to use the methods already
created to calculate this easily.
public double getCaloriesAbsolute()

Returns the following String (with values):
“Serving Size: [amount] Protein: [amount of protein] Fat: [amount of fat] Ca
s:
[amount of ca
s]”
public String getNutrition()
Gold
For gold, add a test method to the VendingMachine to verify your Ingredients class. You should then add additional
methods to Food that will take the total information in each Ingredient and give a similar set of methods as you defined in
Ingredient. The Food versions of the methods will calculate the sum totals of all Ingredients within that Food object at
the given amounts.

Lab 2: Bronze Expected Output
Food Added Successfully: Name: Apple Calories: 120 Cost: 2
Food Added Successfully: Name: Banana Calories: 180 Cost: 1
Vending Machine Interface:
Contains: 10 Food Items
Item 0 is Empty
Item 1 is Empty
Item 2 is Empty
Item 3 is Name: Apple Calories: 120 Cost: 2
Item 4 is Empty
Item 5 is Empty
Item 6 is Name: Banana Calories: 180 Cost: 1
Item 7 is Empty
Item 8 is Empty
Item 9 is Empty
Successfully rejected adding to an occupied spot in the a
ay: Name: Invalid Calories: 0 Cost: 0
Successfully rejected adding to an occupied spot in the a
ay: Name: Invalid Calories: 0 Cost: 0
Successfully rejected adding to index 10
Successfully rejected adding to index -1: Name: Invalid Calories: 0 Cost: 0
Answered Same Day Jan 28, 2021

Solution

Yogesh answered on Jan 28 2021
147 Votes
food.java
food.java
public class Food
{
    
 basic info
   private String name;
   
 related to nutrition
   private int calories;
   private Ingredient[] ingredients;
   private int cost; 
   private static int totalCount; 
 total amount of Food objects Created
   
   
   
 Constructo
   public Food(String newName, int newCalories, int newCost, Ingredient[] ingredientA
ay){
       
 basic info
       name = newName;
       
 related to nutrition
       calories = newCalories;
       cost = newCost; 
       
       ingredients = ingredientA
ay; 
 Update from String to Ingredient
       
       totalCount++;
    }
    
    public String toString(){
        return "Name: " + name + " Calories: " + calories + " Cost: " + cost;
    }
    
    
 method "getIngredients" that returns all the values in the a
ay formatted as a string. 
    public String getIngredients(){
        String str ="Ingredients: ";
        if(ingredients.length == 0){
          str += "None";
        }else if (ingredients.length == 1){ 
 one ingredient
          str += ingredients[0];
        }else{
          
 Handle the case of multiple
          for( int i =0; i < ingredients.length-1; i++){
            str = str + ingredients[i].toString() + ", ";
          }
          str = str + ingredients[ingredients.length-1].toString();
        }
        
        return str;
    }
    
    
 method setIngredients which is an instance method that accepts an a
ay of type String 
    
 and has a return type of void. This should replace the cu
ent ingredient list with the 
    
 ingredient list passed as a parameter. 
    public void setIngredients(Ingredient[] newIngredients){
        ingredients = newIngredients;
    }
    public void addIngredient(Ingredient newIng){
        Ingredient[] temp = new Ingredient[ingredients.length+1];
        for(int i = 0 ; i < ingredients.length; i++){
          temp[i] = ingredients[i];
        }
        temp[temp.length -1 ] = newIng;
        ingredients = temp;
    }
    
    public static int getCount(){
        return totalCount;
    }
}
ingredient.java
ingredient.java
 An Ingredient object contains information about one component of a 
 Food object. Later we will add nutritional information to this. 
public class Ingredient{
    
 instance variables
    private String name; 
    private double amount; 
 in grams
    
 Base constructor to set both variables, Amount is in grams
    public Ingredient(String newName, double newAmount){
        name = newName;
        amount = newAmount;
    }
    
 Returns the name of the Ingredient
    public String toString(){
        return name;
    }
}
vendingmachine.java
vendingmachine.java
public class VendingMachine{
  
      
A
ay of Food objects.
      public Food[] vma
ay;
      public static int a
size = 10;
      
      
Constructo
      public VendingMachine(){
        vma
ay = new Food[a
size];
      }
  
      
 Return the count of all valid Food objects in the machine. 
      
 It should skip over null values of the a
ay and not count them
      public int countFood(){
            int count = 0;
            for(int i=0; i< vma
ay.length -1; i++){
              if (vma
ay[i] != null){
                count +=...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here