Reputation: 21
hey guys im just learning C# in school and am having trouble figuring out how i can use a variable outside of an if statement when that variable is already declared inside an if statement..heres what my program looks like........i have to use the "factor" variable outside of the if statemants because it is part of an equation that i need for a school assignment..if i am missing anything or you need more information, plz dont hesitate to tell me
public caloriesCalculator()
{
InitializeComponent();
}
private void calculate_Click(object sender, EventArgs e)
{
double kilos;
double pounds;
int factor;
double totalcalories;
pounds = double.Parse(lbsTxt.Text);
kilos = pounds * 0.45;
kilosTxt.Text = kilos.ToString();
{
if (maleRadio.Checked && activeRadio.Checked)
{
factor = 15;
}
if (femaleRadio.Checked && activeRadio.Checked)
{
factor = 12;
}
if (maleRadio.Checked && inactiveRadio.Checked)
{
factor = 13;
}
if (femaleRadio.Checked && inactiveRadio.Checked)
{
factor = 10;
}
}
}
Upvotes: 2
Views: 6052
Reputation: 11
You do need to initialize your variables, but if you want to return a number you need to do it with an int type. Void means return nothing. Try using an int method to do this, and return the variable.
I.E. private int radioChecker()
if(this happens) {
factor = 15;
return factor;
}
etc etc
then place radioChecker() inside your void and you can have different things happen based on what it returns.
Upvotes: 1
Reputation: 407
Not clear: But are you saying that this doesn't compile? You need to assign a value (a default) before going inside the if statement.
int factor = 15;
Upvotes: 2