You modified class Height in Problem 1 as follows: public class Height { private
ID: 3765831 • Letter: Y
Question
You modified class Height in Problem 1 as follows:
public class Height
{
private int foot;
private int inch;
public int getFoot()
{
return foot;
}
public void setFoot(int foot)
{
if(foot >0)
this.foot = foot;
}
public int getInch()
{
return inch;
}
public void setInch(int inch)
{
if (inch < 12)
this.inch = inch;
}
}
You are asked to copy the code and add more in this program. Write four constructors for class Height:
Version 1: Take 2 integer arguments and use them to initialize foot and inch
Version 2: Take 1 integer argument and use it to initialize foot. Set inch to 0.
Version 3: Take no arguments. Initialize foot and inch to 0.
Version 4: Take another Height object as argument. Use foot and inch of that Height object to initialize this object’s foot and inch.
[note: do not directly access the instance variables. Always go through the properties.]
Use the following code to test your modified class Height.
public class HeightTest
{
static void Main(string[] args)
{
Height myHeight1 = new Height(5, 7);
Console.WriteLine("My height 1: {0} ft. {1} in.", myHeight1.Foot, myHeight1.Inch);
Height myHeight2 = new Height(5);
Console.WriteLine("My height 2: {0} ft. {1} in.", myHeight2.Foot, myHeight2.Inch);
Height myHeight3 = new Height();
Console.WriteLine("My height 3: {0} ft. {1} in.", myHeight3.Foot, myHeight3.Inch);
Height myHeight4 = new Height(myHeight1);
Console.WriteLine("My height 4: {0} ft. {1} in.", myHeight4.Foot, myHeight4.Inch);
}
}
The following is the expected output.
My height 1: 5 ft. 7 in.
My height 2: 5 ft. 0 in.
My height 3: 0 ft. 0 in.
My height 4: 5 ft. 7 in.
Press any key to continue . . .
Explanation / Answer
class Height
{
private int foot;
private int inch;
public Height(int x,int y)
{
foot=x;
inch=y;
}
public Height(int x)
{
foot=x;
inch=0;
}
public Height(Height h)
{
this.foot=h.foot;
this.inch=h.inch;
}
public Height()
{
foot=0;
inch=0;
}
public int getFoot()
{
return foot;
}
public void setFoot(int foot)
{
if(foot >0)
this.foot = foot;
}
public int getInch()
{
return inch;
}
public void setInch(int inch)
{
if (inch < 12)
this.inch = inch;
}
}
public class HeightTest
{
public static void main(String[] args)
{
Height myHeight1 = new Height(5, 7);
System.out.println("My height 1: "+myHeight1.getFoot()+"ft. "+myHeight1.getInch()+"in.");
Height myHeight2 = new Height(5);
System.out.println("My height 2: "+myHeight2.getFoot()+"ft. "+myHeight2.getInch()+"in.");
Height myHeight3 = new Height();
System.out.println("My height 3: "+myHeight3.getFoot()+"ft. "+myHeight3.getInch()+"in.");
Height myHeight4 = new Height(myHeight1);
System.out.println("My height 4: "+myHeight4.getFoot()+"ft. "+myHeight4.getInch()+"in.");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.