I need to design an Ages class with fields to hold 3 ages and includes a constructor, accessor and mutator method. Also needed is a method that returns the average of the ages.
I also need to write a demo class that creates an instance of Ages class. The demo needs to ask the user to enter 3 ages to be stored in the Ages object. Then the demo displays the average of the ages, as reported by the ages object.
I've written the the 1st program, which compiles o.k. But, I'm not sure it is correct.
Can someone take a look at my 1st class to see if I've set it up properly? Also, can someone give me some direction on how to write the demo program?
Thanks in advance.
/**
Ages Program
*/
public class Ages
{
//Instance variables
private int age1; //holds 1st age
private int age2; //holds 2nd age
private int age3; //holds 3rd age
//Constructor Method
public Ages()
{
//Initialize ages to 0
age1=0;
age2=0;
age3=0;
}
public void setAges (int i, int age)
{
//Set i to age
if (i==1) age1=age;
else if (i==2) age2=age;
else age3=age;
}
public int getAges(int i)
{
//Accessor Method to return ages
if (i==1) return age1;
else if (i==2) return age2;
else return age3;
}
public int getAvg()
{
//Calcuate and return average of 3 ages
int ageAvg;
ageAvg=(int) Math.round((age1+age2+age3)/3.0);
return ageAvg;
}
}