Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a C# console application for this question.The following program defines

ID: 3940169 • Letter: C

Question

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 . . .

Explanation / Answer

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);
}
}