Question: JAVA! Edit the program below and have it show how constructors are used to give initial values to the instance variables defined by the class,
JAVA! Edit the program below and have it show how constructors are used to give initial values to the instance variables defined by the class, or to perform any other startup procedures required to create a fully formed object. Edit the exercise program to include constructor. Create, compile and run the program.
//food class class Food{ int nuts; int flour; int veggies; int grains; //create variables to hold discount int dnuts; int dflour; int dvegs; int dgrains; int total; //total }
class Discount{ public static void main(String bob[]){
//dyanically create object Food f= new Food();
//assigning the values f.nuts = 20; f.flour = 20; f.veggies = 20; f.grains = 50;
//apply discount while(f.nuts>=10){ f.nuts = f.nuts / 10; f.dnuts = f.nuts*3; }
while(f.flour>=20){ f.flour = f.flour / 20; f.dflour = f.flour*5; }
while(f.veggies>=10){ f.veggies = f.veggies / 10; f.dvegs = f.veggies*7; }
while(f.grains>=50){ f.grains = f.grains / 50; f.dgrains = f.grains*10; }
//figure out total discount f.total = f.dnuts + f.dflour + f.dvegs + f.dgrains;
//print System.out.println("Total discount from FreshFood is " + f.total + " dollars."); } }
My note:
I know this would be part of the constructor, but im having issues with constructing the object and using parameters to give value to the object and determine the discount.
//This is a consctructor for Food. Food(int n, int f, int v, int g) { nuts = n; flour = f; veggies = v; grains = g; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
