Create a C console application for this questionThe followin

Create a C# console application for this question.The following program defines class Weight. This class has two publicly accessible instance variables pound and ounce. It also has a constructor that tries to initialize these two instance variables.

// CSC153_A13P02

using System;

publicclassWeight

{

publicint pound;

publicint ounce;

public Weight(int pound, int ounce)

    {

pound = pound;

ounce = ounce;

    }

}

publicclassWeightTest

{

staticvoid Main(string[] args)

    {

Weight weight1 = newWeight(5, 14);

Console.WriteLine(\"Weight 1: {0} lb. {1} oz.\", weight1.pound, weight1.ounce);

    }

}

     However, something is wrong with the program. The instance variables are not initialized properly by the constructors. Output of the program above:

Weight 1: 0lb. 0oz.

Press any key to continue . . .

     Please solve the problem by adding the keyword this in proper places in the constructor. Although there are other ways to solve the problem, you are required to solve it by add the keyword this.

     The following is the expected output after the modifications.

Weight 1: 5lb. 14oz.

Press any key to continue . . .

Solution

Hi, Please find the solution to your problem below. I have added a comment where I have made the change.

using System;

public class Weight
{
public int pound;
public int ounce;

public Weight(int pound, int ounce)
{
this.pound = pound;

this.ounce = ounce;

//\'this\' keyword provides reference to the current object- the object on which constructor is invoked.

}
}
public class WeightTest
{
static void Main(string[] args)
{
Weight weight1 = new Weight(5, 14);
Console.WriteLine(\"Weight 1: {0} lb. {1} oz.\", weight1.pound, weight1.ounce);
}
}

Create a C# console application for this question.The following program defines class Weight. This class has two publicly accessible instance variables pound an
Create a C# console application for this question.The following program defines class Weight. This class has two publicly accessible instance variables pound an

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site