简体   繁体   中英

My code is not returning the correct value

I am trying to program a Form Pay Estimator and it calculates the gross pay, taxes owed, and net pay for an individual employee. For some reason my CalculateTaxes method in my Pay() class is not returning the correct value. This is the code I have here:

In my Pay() class:

{
        //declare variables
        private static int dependants;
        private static double grossPay;

        //property that gets and sets the dependants
        public int NumOfDependents
        {
            get
            {
                return dependants;
            }
            set
            {
                dependants = value;
            }
        }

    //calculates the gross pay for the production worker employee, using their hours
    //worked times their wage and overtime is calculated for the employee, if 
    //applicable
    public double CalculateGrossPay(double hoursWorked, double wageRate)
    {
        grossPay = hoursWorked * wageRate;
            if (hoursWorked > 40)
            {
                grossPay += (.5 * wageRate) * (hoursWorked - 40);
            }
            return grossPay;
    }

    //calculates the gross pay for a salesperson, using their hours worked times their
    //wage rate and then commission is calculated for the employee, based on their 
    //sales amount
    public double CalculateGrossPay(double hoursWorked, double wageRate, double       salesAmount)
    {
        grossPay = hoursWorked * wageRate;
        if (salesAmount <= 10000)
        {
            grossPay += .02 * salesAmount;
        }
        else if (salesAmount > 10000)
        {
            grossPay += .04 * salesAmount;
        }
        return grossPay;
    }

    //calculates the taxes the employee has to pay
    public static double CalculateTaxes()
    {
        int payCutoff = 100 + (100 * dependants);

        if (grossPay <= payCutoff)
        {
            double taxesPaid = .1 * grossPay;
            return taxesPaid;
        }
        else
        {
            double taxesPaid = (.1 * payCutoff) + (.2 * (grossPay - payCutoff));
            return taxesPaid;
        }
    }
}

And in my Form class:

{
    public FormPayEstimator()
    {
        InitializeComponent();
    }

    //closes the application
    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    //closes the application
    private void buttonExit_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    //clears all text boxes, unchecks the salesperson check box, makes the sales amount
    //text box and label invisible and sets the focus back to the hours worked text box
    private void buttonClearForm_Click(object sender, EventArgs e)
    {
        textBoxDependants.Text = "";
        textBoxGrossPay.Text = "";
        textBoxHourlyWageRate.Text = "";
        textBoxHoursWorked.Text = "";
        textBoxNetPay.Text = "";
        textBoxTaxes.Text = "";
        checkBoxSalesperson.Checked = false;
        textBoxSalesAmount.Visible = false;
        labelSalesAmount.Visible = false;
        textBoxHoursWorked.Focus();
    }

    //displays information about the program
    private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Pay Estimator - Version 1.0", "Pay Estimator", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    //if the user checks the salesperson check box the sales amount text box and label
    //become visible to the user and it sets the focus to the sales amount text box
    private void checkBoxSalesperson_CheckedChanged(object sender, EventArgs e)
    {
        textBoxSalesAmount.Visible = true;
        labelSalesAmount.Visible = true;
        textBoxSalesAmount.Focus();
    }

    //displays the font dialog box and allows user to change their font
    private void fontToolStripMenuItem_Click(object sender, EventArgs e)
    {
        fontDialog1.Font = textBoxHoursWorked.Font;
        fontDialog1.Font = textBoxHourlyWageRate.Font;
        fontDialog1.Font = textBoxDependants.Font;
        fontDialog1.Font = textBoxGrossPay.Font;
        fontDialog1.Font = textBoxTaxes.Font;
        fontDialog1.Font = textBoxNetPay.Font;
        fontDialog1.Font = textBoxSalesAmount.Font;
        if (fontDialog1.ShowDialog() != DialogResult.Cancel)
        {
            textBoxHoursWorked.Font = fontDialog1.Font;
            textBoxHourlyWageRate.Font = fontDialog1.Font;
            textBoxDependants.Font = fontDialog1.Font;
            textBoxGrossPay.Font = fontDialog1.Font;
            textBoxTaxes.Font = fontDialog1.Font;
            textBoxNetPay.Font = fontDialog1.Font;
            textBoxSalesAmount.Font = fontDialog1.Font;
        }
    }

    //displays the color dialog box and allows user to change thei font color
    private void colorToolStripMenuItem_Click(object sender, EventArgs e)
    {
        colorDialog1.Color = textBoxHoursWorked.ForeColor;
        colorDialog1.Color = textBoxHourlyWageRate.ForeColor;
        colorDialog1.Color = textBoxDependants.ForeColor;
        colorDialog1.Color = textBoxGrossPay.ForeColor;
        colorDialog1.Color = textBoxTaxes.ForeColor;
        colorDialog1.Color = textBoxNetPay.ForeColor;
        colorDialog1.Color = textBoxSalesAmount.ForeColor;
        if (colorDialog1.ShowDialog() != DialogResult.Cancel)
        {
            textBoxHoursWorked.ForeColor = fontDialog1.Color;
            textBoxHourlyWageRate.ForeColor = fontDialog1.Color;
            textBoxDependants.ForeColor = fontDialog1.Color;
            textBoxGrossPay.ForeColor = fontDialog1.Color;
            textBoxTaxes.ForeColor = fontDialog1.Color;
            textBoxNetPay.ForeColor = fontDialog1.Color;
            textBoxSalesAmount.ForeColor = fontDialog1.Color;
        }
    }

    //calculates the users total gross pay, their taxes owed and their net pay
    private void buttonCompute_Click(object sender, EventArgs e)
    {
        //declares variables
        string inValue;
        double hours, rate, dependants, salesAmount, grossPay, taxes, netPay;

        //assigns variables to values user entered in the hours worked, hourly wage
        //rate and dependants text boxes
        inValue = textBoxHoursWorked.Text;
        hours = double.Parse(inValue);
        inValue = textBoxHourlyWageRate.Text;
        rate = double.Parse(inValue);
        inValue = textBoxDependants.Text;
        dependants = int.Parse(inValue);

        //creates an instance of the Pay class and runs the CalculateGrossPay method
        //for the production workers
        Pay p1 = new Pay();
        grossPay = p1.CalculateGrossPay(hours, rate);

        //checks to see if the sales amount checkbox is checked and if it is, a value
        //is assigned to the salesAmount text box, an instance of the pay class is 
        // createdand the CalculateGrossPay method for a salesperson is run
        if (checkBoxSalesperson.Checked == true)
        {
            inValue = textBoxSalesAmount.Text;
            salesAmount = double.Parse(inValue);
            Pay p2 = new Pay();
            grossPay = p2.CalculateGrossPay(hours, rate, salesAmount);
        }
        //displays the answer in the Gross Pay text box
        textBoxGrossPay.Text = String.Format("{0:c}", grossPay).ToString();

        //runs the CalculateTaxes method from the Pay class and displays the result in
        //the taxes text box
        taxes = Pay.CalculateTaxes();
        textBoxTaxes.Text = String.Format("{0:c}", taxes).ToString();

        //calculates the net pay for an employee and displays the result in the net pay
        //text box
        netPay = grossPay - taxes;
        textBoxNetPay.Text = String.Format("{0:c}", netPay).ToString();
    }
}

}

When I compute the values I got $70 for taxes when it is only meant to be $40. Can anyone tell me why this is happening?

I think one of your problems is that you never set the static property Pay.NumOfDependents . It's hard to tell. Your code is very confusing, what with mixing static properties and such. You would be better off changing those static properties and the static CalculateTaxes method so that they're instance properties and methods. Then, in your code where you calculate the pay based on the employee type, you can write:

Pay p1 = new Pay();
// Here, set the number of dependents.
p1.NumOfDependents = dependents;
if (checkBoxSalesperson.Checked == true)
{
    inValue = textBoxSalesAmount.Text;
    salesAmount = double.Parse(inValue);
    grossPay = p2.CalculateGrossPay(hours, rate, salesAmount);
} 
else
{
    grossPay = p1.CalculateGrossPay(hours, rate);
}

Now when you want to calculate the taxes, you can write:

taxes = p1.CalculateTaxes();

A cleaner design would have you put all of the pertinent properties (hours worked, sales amount, etc.) into the Pay class and then make a single call to calculate gross pay, taxes, etc. That method would set properties on the object like taxes , grossPay , etc. Then you could write:

// code to set properties here ...
// now calculate everything
p1.Calculate();
// and then access the computed properties
textboxGrossPay.Text = string.Format("{0:c}", p1.grossPay);
textboxTaxes.Text = string.Format("{0:c}", p1.taxes);

The idea here it to give the Pay object instance all the information it needs (hours worked, rate, sales amount, number of dependents) and then let it decide how to calculate the pay. That way your user interface code just needs to be concerned with getting data from the user and presenting the results of the calculations.

I'm not going to debug the code for you, but I do have an observation that may help...

CalculateTaxes() seems to rely on the value of private fields such as grossPay. If you don't call your methods in the correct order, those private fields will not be initialized, or may have the wrong value from a previous run. It's generally bad practice to rely on side effects like this for correct calculation. Suggest rewriting your methods not to rely on the previous state of private fields.

paycutoff should be a double, or cast to a double when you do non-integer calculations.

This is an ideal situation for unit tests.

You can write simple function calls to your calculation methods with some numbers, calculate the value you expect, and see if they match.

It would also help for the maintenance part as well as development.

You declared grosspay as static. Value of grosspay reflects in each object. you created p2 and called p2.CalculateGrossPay(hours, rate, salesAmount); It will overwrite the value of grosspay for object p1. When u call calculatetax(), it is estimated on the basis of latest grosspay value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM