Click to See Complete Forum and Search --> : Question on constructors


February 23rd, 2000, 06:40 AM
Question on constructors.
I have an assignemnt that asks for 4 constructors and i have created the first and second but "the third constructor will have two arguments - a numerical measure of distance and units of distance (feet, yards, miles). Using this third constructor, one could instantiate a Distance object by specifying a number as one argument and a unit of measure as a second argument. You must use a code to indicate the unit of measure. Use "f" for feet, "y" for yards, and "m" for miles. The uppercase version of these codes must be valid also."

I am not sure how to make this constructor work.
the following is what I have:

public class Distance
{

private int feet;
private int yards;
private int miles;

// first constructor
public Distance()
{
feet = yards = miles = 0;
}

// second constructor
public Distance(int f)
{
feet = f;
}
// third constructor
public Distance(int y, char y)
{
}


public int getFeet()
{
return feet;
}

public int getYards()
{
return yards;
}

public int getMiles()
{
return miles;
}

public void setFeet(int f)
{
feet = f;
}

public void setYards(int y)
{
yards = y;
}

public void setMiles(int m)
{
miles = m;
}
}

February 23rd, 2000, 03:51 PM
If I understand your queston correctly, you want to figure out how to assign the number to the correct variable?
You could do it like this:


//...
// second constructor
public Distance(int f)
{
feet = f;
}
//
// third constructor
//
public Distance(int y, char units) // Both variables cannot be named y, so I named the second units.
{
switch(units)
{
case 'f':
case 'F':
feet = y;
break;
case 'm':
case 'M':
miles = y;
break;
case 'y':
case 'Y':
yards = y;
break;
default:
feet = yards = miles = 0;
}
}