This is my desired input when both check boxes are selected:
**Input: hours = 45, rate 10.00, both Medical/Dental and 401k check boxes are checked
Here is what I expect to be the output:
· Output: gross pay = 475.00, medical/dental deduction= 50.00, 401k deduction = 23.75, tax = 100.31, net pay = 300.94**
However, I receive this when I run my project after hitting the calculate button and selecting both check boxes (ignore the name):
Name: Joe
Hours: 45
Rate: 10.00
Gross Pay: $400.00
Taxes: $112.50
Net Pay: $337.50
Medical/Dental deduction: $400.00
401k deduction: $20.00
Any help as to what am I doing wrong would be greatly appreciated. I can't seem to figure out the problem.
This is what I have in my project:
These variables are declared at the top of the code:
private const decimal TAX = 0.25m;
private string name = "";
private decimal Gross_pay;
private decimal Taxes;
private decimal Net_Pay;
private decimal annual_salary;
private int NumberOfEmployees;
private decimal deductionMed;
private decimal deduction401k ;
This is where the calculations occur:
private void CalcButton_Click(object sender, EventArgs e)
{ // The “Calculate” button calculates gross pay, taxes, and net pay and then displays name, department, gross pay, taxes, and net pay using currency format for various amounts in the rich text box
// Gross pay= (hours * rate)
// Taxes= (25% of gross pay)
// Net pay (gross pay ?taxes)
//calculate
Gross_pay = Convert.ToInt32(HoursTextBox.Text) * decimal.Parse(RateTextBox.Text);
Taxes = TAX * Gross_pay;
Net_Pay = Gross_pay - Taxes;
annual_salary = Net_Pay;
Taxes = TAX * (Gross_pay - (deductionMed + deduction401k));
//overtime pay
if (Convert.ToInt32(HoursTextBox.Text) >= 41)
{
Gross_pay = Convert.ToInt32(HoursTextBox.Text) * decimal.Parse(RateTextBox.Text) * 1.5m;
DisplayOutPut.Text += "\nOvertime:" + Gross_pay.ToString("C") + "\n";
}
//Medical/Dental and 401k deductions...as well as tax collected.
if (MedicalDentalDeductions.Checked)
{
deductionMed = Gross_pay = Convert.ToInt32(HoursTextBox.Text) * decimal.Parse(RateTextBox.Text) - 50.00m;
}
if (FourOneKDeduction.Checked)
{
deduction401k = Gross_pay * 0.05m;
}
//display
DisplayOutPut.Text = "Name: "+ "";
DisplayOutPut.Text += NameTextBox.Text + "\n";
DisplayOutPut.Text += "Hours: " + HoursTextBox.Text + "\n";
DisplayOutPut.Text += "Rate: " + RateTextBox.Text + "\n";
DisplayOutPut.Text += "Gross Pay: " + Gross_pay.ToString("C") + "\n"; // Hours*Rate
DisplayOutPut.Text += "Taxes: " + Taxes.ToString("C") + "\n";
DisplayOutPut.Text += "Net Pay: " + Net_Pay.ToString("C");
DisplayOutPut.Text += "\nMedical/Dental deduction: " + deductionMed.ToString("C") + "\n401k deduction: " + deduction401k.ToString("C");
//handling the invalid inputs
if (NameTextBox.Text == "")
{ MessageBox.Show("Name is missing.", "Error"); }
if (Convert.ToInt32(HoursTextBox.Text) >= 70)
{ MessageBox.Show("Please Enter a Valid hour.", "Invalid data type."); }
if (RateTextBox.Text == "" && (RateTextBox.Text == ","))
{ MessageBox.Show("Please Enter a valid amount.", "Invalid data type ($)"); }
if (Convert.ToInt32(HoursTextBox.Text) >= 70)
{ MessageBox.Show("You have exceeded the maximum hours per week."); }
else if (Convert.ToInt32(HoursTextBox.Text) < 10)
{ MessageBox.Show("You cannot input less than 10 hours."); }
if (Convert.ToDecimal(RateTextBox.Text) < 9.75m)
{ MessageBox.Show("Please enter the minimum wage."); }
}
These are the methods for the check boxes:
private void MedicalDentalDeductions_CheckedChanged(object sender, EventArgs e)
{
}
private void FourOneKDeduction_CheckedChanged(object sender, EventArgs e)
{
}
You should really split your calculations into separate methods as it is much easier to debug. In saying that, I have not tested the following, but each method should produce the values you're after. It is just a matter of building your DisplayOutPut using values derived from these methods (I want to leave some work for you to do).
The first thing you should be calculating is the gross pay:
private double calculateGrossPay (double hours, double rate)
{
double result = 0.00;
double standardHours = 0.00;
double overtimeHours = 0.00;
if (hours > 40)
{
overtimeHours = (hours - 40) * (rate * 1.5);
standardHours = 40 * rate;
}
else
{
standardHours = hours * rate;
}
result = standardHours + overtimeHours;
return result;
}
Then calculate the tax:
private double caculateTax (double gross, double tax)
{
double result = 0.00;
result = gross * tax; // assuming tax is represented as 0.25 for 25%
return result;
}
Followed by calculating the deductions:
private double caclulate401k (double gross) // Or net?
{
double result = 0.00;
result = gross * 0.05;
return result;
}
private double calculateMedical (double gross) // Or net?
{
double result = 0.00;
result = 50.00; // I figure this should be an actual calculation, if medical is always $50, waste of a method...
return result;
}
Finally, calculate the net.
private double calculateNet (double gross, double tax, double med, double 401k)
{
double result = 0.00;
double deductions = tax + med + 401k;
result = gross - deductions;
return result;
}
Related
Example code:
//money deposit
Console.Write("Enter said amount of money: ");
moneyres = Convert.ToDouble(Console.ReadLine());
if (moneyres < ticket)
{
double dif = ticket - moneyres;
Console.Write("Oh, sorry you are " + dif + " dollar(s) sort.\nPlease enter more money so you can purchase the ticket: ");
double m2 = Convert.ToDouble(Console.ReadLine());
double m3 = dif - m2;
while (m3 > 0)
{
Console.Write("Oh, sorry you are " + m3 + " dollar(s) sort.\nPlease enter more money so you can purchase the ticket: ");
}
}
else if (moneyres > ticket)
{
change = moneyres - ticket;
Console.WriteLine("So your change is: " + change + " dollar(s).\nHere you go. Have fun!");
}
else
{
Console.WriteLine("Here you go. Have fun!");
}
So let's say the ticket is 10 bucks and someone puts 5. Then the difference is going to be 5. Then lets say he adds 2 more.
How can I do a loop till the amount hits 0? (I am new to coding btw).
You can do all of this in a while loop.
double totalValue = 0.0;
while(totalValue < ticket)
{
Console.Write("Enter said amount of money: ");
moneyres = Convert.ToDouble(Console.ReadLine());
totalValue += moneyres;
if (totalValue > ticket)
{
// Enough
}
else
{
// Not enough
}
}
You should look into a while loop. Something like while(UserInput < ticket). UserInput in this case is the amount that the user pays.
So I did this. Thanks a lot for the suggestions!
double tot = 0.0;
while (tot < ticket)
{
string sp = "Enter money: ";
Console.Write(sp);
moneyres = Convert.ToDouble(Console.ReadLine());
tot += moneyres;
if (tot > ticket)
{
change = tot - ticket;
Console.WriteLine("Alright here is your change. That's " + change + " dolars.And
here is your ticket!\nEnjoy your ride!");
}
else if (tot==ticket)
{
Console.WriteLine("That's just perfect! Here you go!\nEnjoy your ride!");
}
else
{
Console.WriteLine("You did not enter enough money.");
}
}
Console.ReadKey();
I've just started studying the C#. And bumped into a problem:
When I use the Console.WriteLine in the Main method, it works just fine. However, when I try to break the code into methods, the WriteLine does not return anything. (I use Visual Studio to build and compile the project).
The task is to find a final amount of money a person would get when depositing money based on monthly capitalization. I kinda suspect I just messed up some trivial thing, but would still appreciate an explanation :) Thanks
The code without methods:
using System;
class Program
{
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
//Separating the input string into substrings
string[] separated = userInput.Split(' ');
//Getting the main variables
double sum1 = double.Parse(separated[0]);
double oneMonthPercentage = double.Parse(separated[1]) / 1200; //find a montly amount in percent = amount / 12 month / 100
double months = double.Parse(separated[2]);
double initialSum = sum1;
//Calculation of the final ammount
for (int i = 1; i <= months; i++)
{
sum1 += sum1 * oneMonthPercentage;
}
//Output
Console.WriteLine("Ammount: " + initialSum);
Console.WriteLine("Percentage: " + oneMonthPercentage * 1200 + "%");
Console.WriteLine("Time: " + months);
Console.WriteLine("Final amount: " + Math.Round(sum1, 2));
}
}
OUTPUTS - no_methods
The code with methods (WriteLine does not work):
using System;
class Program
{
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
}
//Separating string into substrings
public static string[] SeparateString(string userInput)
{
string[] separated = userInput.Split(' ');
return separated;
}
//calculating the final amount at the end of deposit time
public static double Calculate(string userInput)
{
// defining main variables for calculation
double sum1 = double.Parse(SeparateString(userInput)[0]);
double oneMonthPercentage = double.Parse(SeparateString(userInput)[1]) / 1200;
double months = double.Parse(SeparateString(userInput)[2]);
double initialSum = sum1;
//calculation as to the formula
for (int i = 1; i <= months; i++)
{
sum1 += sum1 * oneMonthPercentage;
}
//Output
Console.WriteLine("Ammount: " + initialSum);
Console.WriteLine("Percentage: " + oneMonthPercentage * 1200 + "%");
Console.WriteLine("Time: " + months);
Console.WriteLine("Final amount: " + Math.Round(sum1, 2));
return sum1;
}
}
OUTPUTS - with_methods
You need to call those methods to make them work. Right now you are only calling the initial WriteLine and ReadLine
You don't call any method. You should call Calculate() method:
static void Main()
{
//User input
Console.WriteLine("Enter the initial amount, percentage, and deposit time (months)");
string userInput = Console.ReadLine();
var result = Calculate(userInput); // call here
}
I'm creating a simple calculator for my C# class and having some trouble with the final calculations.
I've declared my variables and I'm using simple if then statements for the order. My problem is, after I've defined my variables, the information they contain doesn't change when the calculation is performed, they simply just output zero as defined by the original value instead of outputting the new amount from the if statement (TotalCost, Tax, TotalWithTax).
I've input different numbers in place of the zero and the formulas work, it's just that the value never changes to what I have stated in the
If statements. Is it not possible to adjust the value of a variable from within a if statement?
What is another possible way to go about this if that is the case?
Trying to keep it simple as I'm not really proficient with console programming.
string SizeName = "";
double SizeCost = 0;
string ToppingName = "";
double ToppingCost = 0;
double TotalCost = (SizeCost + ToppingCost);
double Tax = (TotalCost*0.085);
double TotalWithTax = (TotalCost + Tax);
//Print a greeting message.
Console.WriteLine("Welcome to the Central Pizza Parlor!");
//Ask if the customer would like to order a pizza.
Console.WriteLine("Would you like to order a pizza today? Enter y for Yes or n for No.");
string Order = Console.ReadLine();
//Start the order if answer is Yes, if not, then exit the program.
if (Order == "y")
{
//Continue with order.
Console.WriteLine("Great! Let's get started, please pick the size of your pizza:");
Console.WriteLine("1 - Small $5.00");
Console.WriteLine("2 - Medium $7.00");
Console.WriteLine("3 - Large $9.00");
//Get pizza size for order.
Console.WriteLine("Please enter the number for the pizza size you would like.");
string sizeAsAString = Console.ReadLine();
int size = Convert.ToInt32(sizeAsAString);
//Use If Else statement to set the variable value for SizeCost.
if (size == 1)
{
SizeCost = 5.0;
SizeName = ("Small");
}
else if (size == 2)
{
SizeCost = 7.0;
SizeName = ("Medium");
}
else if (size == 3)
{
SizeCost = 9.0;
SizeName = ("Large");
}
//Have Customer select toppings.
Console.WriteLine("Please select which topping you would like on your pizza.");
;
Console.WriteLine("1 - Pepperoni $2.00");
Console.WriteLine("2 - Ham $2.00");
Console.WriteLine("3 - Onions $1.00");
Console.WriteLine("4 - Mushrooms $1.00");
Console.WriteLine("5 - Green Peppers $1.00");
Console.WriteLine("Please enter the number for the corresponding topping you would like.");
string toppingAsAString = Console.ReadLine();
int topping = Convert.ToInt32(toppingAsAString);
//Use If Else statement to set the variable value for ToppingCost.
if (topping == 1)
{
ToppingCost = 2.0;
ToppingName = ("Pepperoni");
}
else if (topping == 2)
{
ToppingCost = 2.0;
ToppingName = ("Ham");
}
else if (topping == 3)
{
ToppingCost = 1.0;
ToppingName = ("Onions");
}
else if (topping == 4)
{
ToppingCost = 1.0;
ToppingName = ("Mushrooms");
}
else if (topping == 5)
{
ToppingCost = 1.0;
ToppingName = "Green Peppers";
}
//Display order details.
Console.WriteLine("Here are the details for your order.");
Console.WriteLine("Thank you for your business!");
Console.WriteLine("You can pick up your pizza in 25 minutes!");
//Show current time of order.
DateTime now = DateTime.Now;
Console.WriteLine("Time Ordered: "+now+" ");
//Show Current time of order with additional 25 minutes for pickup.
DateTime pickup = DateTime.Now.AddMinutes(25);
Console.WriteLine("Pick Up At: "+pickup+" ");
//Output Pizza Size.
Console.WriteLine("Size: " +SizeName+ " ");
//OutPut Topping name.
Console.WriteLine("Topping: " +ToppingName+ " ");
Console.WriteLine("---------------");
//Output total price of size and topping chosen.
Console.WriteLine("Pizza Price: $ "+TotalCost+" ");
//Output tax amount.
Console.WriteLine("Tax: $" +Tax+ " ");
//Output total price with tax.
Console.WriteLine("Total Price: $" +TotalWithTax+ " ");
}
else
{
//Exit the program because the customer does not want to order a pizza.
Console.WriteLine("Alright, have a great day!");
}
Console.ReadLine();
}
}
}
All your calcualtions are at the top(in declaration). Performing your calculations with defaults will not output desired result.
double TotalCost = (SizeCost + ToppingCost);
double Tax = (TotalCost*0.085);
double TotalWithTax = (TotalCost + Tax);
Move these calcualtions to bottom (before outputting).
public class Program
{
public static void Main()
{
string SizeName = "";
double SizeCost = 0;
string ToppingName = "";
double ToppingCost = 0;
double TotalCost =0;
double Tax = 0;
double TotalWithTax = 0;
//Print a greeting message.
Console.WriteLine("Welcome to the Central Pizza Parlor!");
//Ask if the customer would like to order a pizza.
Console.WriteLine("Would you like to order a pizza today? Enter y for Yes or n for No.");
string Order = Console.ReadLine();
//Start the order if answer is Yes, if not, then exit the program.
if (Order == "y")
{
//Continue with order.
Console.WriteLine("Great! Let's get started, please pick the size of your pizza:");
Console.WriteLine("1 - Small $5.00");
Console.WriteLine("2 - Medium $7.00");
Console.WriteLine("3 - Large $9.00");
//Get pizza size for order.
Console.WriteLine("Please enter the number for the pizza size you would like.");
string sizeAsAString = Console.ReadLine();
int size = Convert.ToInt32(sizeAsAString);
//Use If Else statement to set the variable value for SizeCost.
if (size == 1)
{
SizeCost = 5.0;
SizeName = ("Small");
}
else if (size == 2)
{
SizeCost = 7.0;
SizeName = ("Medium");
}
else if (size == 3)
{
SizeCost = 9.0;
SizeName = ("Large");
}
//Have Customer select toppings.
Console.WriteLine("Please select which topping you would like on your pizza.");
;
Console.WriteLine("1 - Pepperoni $2.00");
Console.WriteLine("2 - Ham $2.00");
Console.WriteLine("3 - Onions $1.00");
Console.WriteLine("4 - Mushrooms $1.00");
Console.WriteLine("5 - Green Peppers $1.00");
Console.WriteLine("Please enter the number for the corresponding topping you would like.");
string toppingAsAString = Console.ReadLine();
int topping = Convert.ToInt32(toppingAsAString);
//Use If Else statement to set the variable value for ToppingCost.
if (topping == 1)
{
ToppingCost = 2.0;
ToppingName = ("Pepperoni");
}
else if (topping == 2)
{
ToppingCost = 2.0;
ToppingName = ("Ham");
}
else if (topping == 3)
{
ToppingCost = 1.0;
ToppingName = ("Onions");
}
else if (topping == 4)
{
ToppingCost = 1.0;
ToppingName = ("Mushrooms");
}
else if (topping == 5)
{
ToppingCost = 1.0;
ToppingName = "Green Peppers";
}
TotalCost = (SizeCost + ToppingCost);
Tax = (TotalCost*0.085);
TotalWithTax = (TotalCost + Tax);
//Display order details.
Console.WriteLine("Here are the details for your order.");
Console.WriteLine("Thank you for your business!");
Console.WriteLine("You can pick up your pizza in 25 minutes!");
//Show current time of order.
DateTime now = DateTime.Now;
Console.WriteLine("Time Ordered: "+now+" ");
//Show Current time of order with additional 25 minutes for pickup.
DateTime pickup = DateTime.Now.AddMinutes(25);
Console.WriteLine("Pick Up At: "+pickup+" ");
//Output Pizza Size.
Console.WriteLine("Size: " +SizeName+ " ");
//OutPut Topping name.
Console.WriteLine("Topping: " +ToppingName+ " ");
Console.WriteLine("---------------");
//Output total price of size and topping chosen.
Console.WriteLine("Pizza Price: $ "+TotalCost+" ");
//Output tax amount.
Console.WriteLine("Tax: $" +Tax+ " ");
//Output total price with tax.
Console.WriteLine("Total Price: $" +TotalWithTax+ " ");
}
else
{
//Exit the program because the customer does not want to order a pizza.
Console.WriteLine("Alright, have a great day!");
}
Console.ReadLine();
}
}
Fiddler Demo
You set TotalCost before changing the Values of SizeCost or ToppingCost.
Move these lines
double TotalCost = (SizeCost + ToppingCost);
double Tax = (TotalCost*0.085);
double TotalWithTax = (TotalCost + Tax);
to after your input section.
I try using the do-while loop but it doesn't do anything after I enter the input and initiate the button click event. It is supposed to calculate out the amount and list for all the years following until it is <=40,000. I can get the program to run without the loop but not with it.
private double InterestEarned(double AMT, double AIR = 0.07)
{
return AMT * AIR;
}
private double InheritanceAmount(double BAL, double IR, double AIR = 0.07)
{
return (BAL * IR * AIR) - 40000;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
double AMT;
AMT = (double.Parse(textBox1.Text));
if (radioButton1.Checked==true)
{
do
{
const double IR3 = 0.03;
double BAL, IR, earn;
int year = 2014;
AMT = (double.Parse(textBox1.Text));
IR = IR3;
year++;
BAL = InheritanceAmount(AMT, IR);
earn = InterestEarned(AMT);
listBox1.Items.Add("You have chosen a 3% inflation rate. Your investment starts at" + AMT.ToString("C") + " and earn 7% a year. You withdraw $40,000 a year.");
listBox1.Items.Add("Year" + "\t" + "Interest Earned" + "\t" + "Balance");
listBox1.Items.Add(year++ + "\t" + earn.ToString("C") + "\t" + BAL.ToString("C"));
} while (AMT > 40000);
}
else if (radioButton2.Checked==true)
{
do
{
const double IR4 = 0.04;
double BAL, IR, earn;
int year = 2014;
AMT = (double.Parse(textBox1.Text));
IR = IR4;
year++;
BAL = InheritanceAmount(AMT, IR);
earn = InterestEarned(AMT);
listBox1.Items.Add("You have chosen a 4% inflation rate. Your investment starts at" + AMT.ToString("C") + " and earn 7% a year. You withdraw $40,000 a year.");
listBox1.Items.Add("Year" + "\t" + "Interest Earned" + "\t" + "Balance");
listBox1.Items.Add(year++ + "\t" + earn.ToString("C") + "\t" + BAL.ToString("C"));
} while (AMT > 40000);
}
else
{
MessageBox.Show("Please select an inflation rate.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The do...while loop is conditional on the value of AMT being greater than 40000. But the value of AMT only comes from the user (via the textbox) and is never changed again. So the loop just happens forever (which, since it is being run on your UI thread, will lock the UI). Either your condition is wrong or you need to be changing the value of AMT within the loop.
Your while condition is based on the AMT variable (> 40000). You initialize that variable correctly before the do while. However, you also reinitialize that variable inside the do while loop and this is why the variable never reach the condition that would make it exit the your do while loop.
The first thing to do here is to comment the line where the AMT variable is set back to it's original value:
do
{
const double IR3 = 0.03;
double BAL, IR, earn;
int year = 2014;
//Comment the line below
//AMT = (double.Parse(textBox1.Text));
IR = IR3;
year++;
BAL = InheritanceAmount(AMT, IR);
earn = InterestEarned(AMT);
//...
} while (AMT > 40000);
The next thing you should do is to increase the AMT based on the earn value:
AMT += earn;
The last thing you should consider is way to avoid infinite loop when the AMT original value is <= 0 or when the interest are set to 0.
I have this windows app Cafe that allows the user to make their selection and then it displays the cost of the items chosen, subtotal, tax, total, number of transactions made that day, and I need it to display the total sales tax collected as well. I figured calculating this would be similar to how I calculated # of transactions, but I have yet to figure it out. Any ideas?
public partial class Form1 : Form
{
int clicks = 0;
double totalSalesTaxCollected = 0;
public Form1()
{
InitializeComponent();
InitializeControls();
}
private void button1_Click(object sender, EventArgs e)
{
clicks++;
displayBill();
}
private void displayBill()
{
// int[] listArray = listBox1.getSelectedIndices();
// SelectedIndexCollection listArray = listBox1.SelectedIndices;
double localTax = 0.01;
double stateTax = 0.06;
double tax;
double subTotal = 0;
double total;
//Set the text area to non-edit mode and start
//with an empty string.
textBox1.ReadOnly = true;
textBox1.Text = "";
textBox1.AppendText(" C# KIOSK A LA CARTE\n\n");
textBox1.AppendText("--------------- Welcome ----------------\n\n");
//Calculate the cost of the items ordered.
for (int index = 0; index < listBox1.SelectedIndices.Count; index++)
{
subTotal = subTotal + yourChoicesPrices[listBox1.SelectedIndices[index]];
}
tax = (localTax + stateTax) * subTotal;
total = subTotal + tax;
//Display the costs.
for (int index = 0; index < listBox1.SelectedIndices.Count; index++)
{
textBox1.AppendText(yourChoicesItems[listBox1.SelectedIndices[index]] +"\n");
}
textBox1.AppendText("\n");
textBox1.AppendText("SUB TOTAL\t\t" + String.Format("{0:C}", subTotal) + "\n");
textBox1.AppendText("TAX \t\t"+ String.Format("{0:C}" , tax) + "\n");
textBox1.AppendText("TOTAL \t\t"+ String.Format("{0:C}" , total) + "\n\n");
textBox1.AppendText("\n");
textBox1.AppendText("Thank you - Have a Nice Day\n\n");
textBox1.AppendText("\n");
textBox1.AppendText("Total sales: \t\t" + clicks + "\n" );
textBox1.AppendText("Total sales tax collected: \t\t" + totalSalesTaxCollected);
//Reset list array.
listBox1.ClearSelected();
}
After
tax = (localTax + stateTax) * subTotal;
total = subTotal + tax;
Add totalSalesTaxCollected += tax;
Unless I missed it, I think you need.. and I'm guessing after this line:
tax = (localTax + stateTax) * subTotal;
total = subTotal + tax;
Add:
totalSalesTaxCollected+=total;