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.
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
}
What I am trying to do is limit the withdrawal amount by $20 increments up to $500. I know I am missing some simple element in here to do this. My code worked until I tried to do the increments of 20.
double AccountBalance = 1500;
double WithdrawalAmount;
WithdrawalAmount = double.Parse(textInput.Text);
Double MaxWithdrawalAmount = 0;
for (MaxWithdrawalAmount = 0; MaxWithdrawalAmount <= 500; MaxWithdrawalAmount += 20)
{
if (WithdrawalAmount == MaxWithdrawalAmount)
{
double Total = (AccountBalance - WithdrawalAmount);
textTotal.Text = ("Total amount" + Convert.ToString(Total));
}
else
{
textError.Text = ("Only Increments of $20 allowed for withdraw up to $100");
textTotal.Text = ("" + AccountBalance);
}
}
You should handle your loop in a different way
bool ok = false;
for (MaxWithdrawalAmount = 0; MaxWithdrawalAmount <= 500; MaxWithdrawalAmount += 20)
{
if (WithdrawalAmount == MaxWithdrawalAmount)
{
double Total = (AccountBalance - WithdrawalAmount);
textTotal.Text = "Total amount" + Convert.ToString(Total);
ok = true;
break;
}
}
if (!ok)
{
textError.Text = ("Only Increments of $20 allowed for withdraw up to $100");
textTotal.Text = ("" + AccountBalance);
}
I have moved the error message outside the loop. If, inside the loop I find the correct value for withdrawal then I stop the loop and set a flag to avoid the final error message
Side note, if you don't need double values the whole code could be reduced to a few lines using the remainder operator . For example
int WithdrawalAmount = 120;
if ((WithdrawalAmount % 20) == 0)
... good ...
else
... bad ...
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;
}
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;