I apologize if this is a really simple solution...
So I'm trying to get an Ending Balance from 4 inputs, those being
- Starting Balance
- Number of months that have elapsed
- User Specified yearly interest rate
- and a optional monthly contribution that the user can put in. This is what I would imagine the equation to be
balance = contribution + balance + (INTEREST_RATE * balance) + (yearly * balance);
Everything is fine until the compiler states that Use of unassigned local variable 'contribution' This really confuses me because at the comment at the top of the code I have stated that contribution will be an int.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calculateButton_Click(object sender, EventArgs e)
{
// Constant for the monthly interest rate.
const decimal INTEREST_RATE = 0.005m;
// Local variables
decimal balance; // The account balance
int months; // The number of months
int contribution;
int count = 1; // Loop counter, initialized with 1
decimal yearly;
// Get the starting balance.
if (decimal.TryParse(txtStartBalance.Text, out balance))
{
// Get the number of months.
if (int.TryParse(txtMonths.Text, out months))
{
// Get the yearly interest rate
if (decimal.TryParse(txtYearly.Text, out yearly))
{
//Get monthly contribution
if (int.TryParse (txtMonthly.Text, out contribution));
}
// The following loop calculates the ending balance.
while (count <= months)
{
// Add this month's interest to the balance.
balance = contribution + balance + (INTEREST_RATE * balance) + (yearly * balance);
// Display this month's ending balance.
if (rdoEnglish.Checked == false)
lstDetails.Items.Add("ʻO ka pale hope " + "no ka mahina " + count + " ʻO " + balance.ToString("c"));
else
lstDetails.Items.Add("The ending balance for " + "month " + count + " is " + balance.ToString("c"));
// Add one to the loop counter.
count = count + 1;
}
// Display the ending balance.
txtEnding.Text = balance.ToString("c");
Again thank you for taking the time to help me.
contribution. What if the value in eithertxtYearly.TextortxtMonthly.Textdoes not successfully parse as a decimal or int (respectively)? If that happens, andcount <= monthsis still true, then you skip the assignment ofcontribution, and then try to use it.contributionwill be set to 0 iftxtMonthly.Textfails to parse, sinceoutparameters must be assigned. The problem is just withtxtYearly.Text.