Question: 5 . The below program shows how constructor is used to give initial values to the instance variables defined by the class, or to perform

5.The below program shows how constructor is 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. /* Unit 3 Lab Ex:5
Same as Ex:4 but will show how constructor is used to give initial values to the instance variables defined by the class, or to perform
any other start up procedures required to create a fully formed object.
*/
// food class
class Food
{
int nuts; //nuts
int flour; // flour
int veggies; // veggies
int grains; // grains
// create variables to hold discount
int dnuts;
int dflour;
int dvegs;
int dgrains;
int total; // total
}
// object of type vehicle
class Discount
{
public static void main(String bob[])
{
// dynaically 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; // discount of nuts
f.dnuts = f.nuts *3;
}
while(f.flour >=20)
{
f.flour = f.flour /20; // discount of flour
f.dflour = f.flour *5;
}
while(f.veggies >=10)
{
f.veggies = f.veggies /10; // discount of veggies
f.dvegs = f.veggies *7;
}
while(f.grains >=50)
{
f.grains = f.grains /50; // discount of grains
f.dgrains = f.grains *10;
}
// figure out total discount
f.total = f.dnuts + f.dflour + f.dvegs + f.dgrains;
// print
System.out.println("Totl discount from FreshFoods is "+ f.total +" dollars.");
}
}
Edit Exercise 4
program to include constructor. Create, compile and run the program. Provide screen capture and code.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!