Listbox unassigned variable - c#

Full disclosure here, I am a student doing homework. I have 2 listboxes with items that can be selected. What is said in them is not needed to be extracted. I wrote the code out and everything works except I get an error saying "use of unassigned variable" on 3 variables at the end of the code. They are locFees, days, and registration. Can anyone tell me what I am doing wrong that is causing the variables to not have a value?
private void btnCalc_Click(object sender, EventArgs e)
{
double registration, lodging, total, days, locFees;
int workshopIndex, locationIndex;
if (lbWorkshop.SelectedIndex != -1)
{
workshopIndex = lbWorkshop.SelectedIndex;
switch (workshopIndex)
{
case 0:
days = 3;
registration = 1000;
break;
case 1:
days = 3;
registration = 800;
break;
case 2:
days = 3;
registration = 1500;
break;
case 3:
days = 5;
registration = 1300;
break;
case 4:
days = 1;
registration = 500;
break;
}
}
else
{
MessageBox.Show("You didn't select a workshop.");
}
if (lbLocation.SelectedIndex != -1)
{
locationIndex = lbLocation.SelectedIndex;
switch (locationIndex)
{
case 0:
locFees = 150;
break;
case 1:
locFees = 225;
break;
case 2:
locFees = 175;
break;
case 3:
locFees = 300;
break;
case 4:
locFees = 175;
break;
case 5:
locFees = 150;
break;
}
}
else
{
MessageBox.Show("You didn't select a city.");
}
lodging = locFees * days;
total = registration + lodging;
}

Can anyone tell me what I am doing wrong that is causing the variables to not have a value?
Sure - you're ignoring the possibility that workshopIndex isn't 0, 1, 2, 3 or 4.
If you believe that should never happen, just add:
default:
throw new InvalidOperationException("Invalid selected index " + workshopIndex);
Or if you just want to use some defaults, do something like:
default:
days = 1;
registration = 100;
break;
That's the first way you can end up with days and registration unassigned.
Next, there's the fact that you only go into the switch block at all if lbWorkshop.SelectedIndex != -1. Your else block is just:
else
{
MessageBox.Show("You didn't select a workshop.");
}
... so after that else block, you're going to continue. You probably want:
else
{
MessageBox.Show("You didn't select a workshop.");
return;
}
You've then got the same problem for locFees, in terms of both the switch statement and the else block.
One thing to learn from this: be grateful that the compiler spotted these for you. It's stopped you from running code which definitely had bugs in. That's always a good thing.

Related

Switch statement using text box within forms

I am building a form that takes an input number from a text box and then will take the number that was input, and display the roman numeral equivalent in another text box.
My Form:
private void convertButton_Click(object sender, EventArgs e)
{
int numberInput;
switch (numberInput)
This is where I keep getting an error code. The "switch (numberInput)" is seen as and unassigned local variable. How do I assign it so that it will be able to access all of the case integers?
{
case 1:
outputTextBox.Text = "I";
break;
case 2:
outputTextBox.Text = "II";
break;
case 3:
outputTextBox.Text = "III";
break;
case 4:
outputTextBox.Text = "IV";
break;
case 5:
outputTextBox.Text = "V";
break;
case 6:
outputTextBox.Text = "VI";
break;
case 7:
outputTextBox.Text = "VII";
break;
case 8:
outputTextBox.Text = "VIII";
break;
case 9:
outputTextBox.Text = "IX";
break;
case 10:
outputTextBox.Text = "X";
break;
default:
MessageBox.Show("Please enter and number between 1 and 10. Thank you!");
break;
}
Cause your variable is not assigned yet int numberInput; and so the error. You said input is coming from a TextBox, in that case do like below assuming textbox1 is your TextBox control instance name
int numberInput = Convert.ToInt32(this.textbox1.Text.Trim());
Convert.ToInt32 may throw an exception if the parsing is unsuccessful. Another method is to Int.Parse:
int numberInput = int.Parse(textbox1.Text.Trim());
or better yet
int numberInput;
if(int.TryParse(textbox1.Text.Trim(), out numberInput))
{
switch (numberInput)
...
}

Thrown system.exception.stackoverflowexception C#

In my C# windows form application, there is a combo box that has 3 options in it, when selecting second one a switch command that checks options of another combo box throws and exception of type stack overflow, with this details:
System.StackOverflowException occurred
HResult=0x800703E9
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
Update:
this is the event of index change in combo box:
private void cmbxDoorType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbxDoorType.SelectedIndex == 0)
{
chkTopBlock.Enabled = true;
if(chkTopBlock.Checked)
cmbxTopBlockConfig.Enabled = true;
cmbxTopSideConfig.Enabled = true;
txtDoorHeight.ReadOnly = false;
txtTotalWidth.Visible = false;
lblTotalWidth.Visible = false;
lblDoorBaleWidth.Enabled = false;
}
else if (cmbxDoorType.SelectedIndex == 1)
{
txtTotalWidth.Visible = false;
lblTotalWidth.Visible = false;
lblDoorBaleWidth.Enabled = false;
cmbxTopBlockConfig.Enabled = false;
chkTopBlock.Enabled = false;
txtDoorHeight.ReadOnly = true;
cmbxTopSideConfig.Enabled = false;
}
else
{
chkTopBlock.Enabled = true;
if (chkTopBlock.Checked)
cmbxTopBlockConfig.Enabled = true;
cmbxTopSideConfig.Enabled = true;
txtDoorHeight.ReadOnly = false;
txtTotalWidth.Visible = true;
lblTotalWidth.Visible = true;
lblDoorBaleWidth.Enabled = true;
}
Prediction();
}
this is the prediction methode than exception ocours in:
internal void Prediction ()
{
if (Globals.ProjectType=="Gama")
{
int TotalHeight_=0;
double DesignHeight_=0;
int TotalWidth_=0;
double LeftDis = 0;
double RightDis = 0;
double RowsTotalHeight_=0;
double TopBlockHeight_=0;
double thisDoorHeight_ = 0;
int DoorHeight_=0;
int DoorWidth_=0;
double DoorBaleWidth_=0;
try
{
switch (cmbxLeftSideConfig.SelectedIndex) //exception thrown here
{
case 0:
LeftDis = GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 2:
LeftDis = GamaGlobals.Constants.GP115Body + GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 3:
LeftDis = GamaGlobals.Constants.GP114Body + GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 4:
LeftDis = GamaGlobals.Constants.GP117Height - GamaGlobals.Constants.InsertOffset;
break;
case 1:
LeftDis = 0;
break;
}
switch (cmbxRightSideConfig.SelectedIndex)
{
case 0:
RightDis = GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 2:
RightDis = GamaGlobals.Constants.GP115Body + GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 3:
RightDis = GamaGlobals.Constants.GP114Body + GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 4:
RightDis = GamaGlobals.Constants.GP117Height - GamaGlobals.Constants.InsertOffset;
break;
case 1:
RightDis = 0;
break;
}
}
Something in your cmbxDoorType_SelectedIndexChanged, or another SelectedIndexChanged event will retrigger your event again, which makes it a StackOverFlowException after a couple of seconds
in "prediction" method there was a line that changes a textbox value, and that text box itself has a value changed event that triggers "prediction" again.
so it's solved.
just as another question, is there a way to change textbox/numericupdown controls value programmatically without triggering its change event?
for example, if the user changes it, it triggers event but when its programmatically changed, the event does not trigger.
hm??

Switch case goes to default except one case

when i tried to use the Switch case function, it goes always to the default message besides case 5:
private void btnCandlesLight_Click(object sender, EventArgs e)
{
int result;
result = Convert.ToInt32(textBox1.Text);
switch(result)
{
case 1:
day1.Start();
candlesOne();
break;
case 2:
day2.Start();
candlesTwo();
break;
case 3:
day3.Start();
candlesThree();
break;
case 4:
day4.Start();
candlesFour();
break;
case 5:
day5.Start();
candlesFive();
break;
case 6:
day6.Start();
candlesSix();
break;
case 7:
day7.Start();
candlesSeven();
break;
case 8:
day8.Start();
candlesEight();
break;
default:
MessageBox.Show("Enter new day");
break;
}
}
When I Enter the value 1 for example to the text box, the default case works, but only when I enter the value 5 it works perfectly.
If you want to see the difference between the function "candlesOne" to "candlesFive":
The "c" variable is a variable of the seconds. i tried to use a timer in a way of lighting up the candles every 2-3 seconds.
public void candlesOne()
{
firedmatch.Left = firedmatch.Left + 100;
if (c == 1)
{
candle1.Visible = true;
}
if (c == 3)
{
candle2.Visible = true;
}
}
and:
public void candlesFive()
{
firedmatch.Left = firedmatch.Left + 100;
if(c == 1)
{
candle1.Visible = true;
}
if(c == 3)
{
candle2.Visible = true;
}
if(c == 5)
{
candle3.Visible = true;
}
if(c == 7)
{
candle4.Visible = true;
}
if(c == 11)
{
candle5.Visible = true;
}
}
I haven't found a mistake,
can you guys help me?
Thanks
Have you checked if you really get for example (int)1 as a result of the "1" input from your conversion?
On a broader scale, there is a lot of repetition in your code, you should consider refactoring it a little.
In your CandlesOne and CandlesFive methods, you use a c variable, no idea what that is or where it comes from. Those two methods (and probably the other CandlesXXX() do the same kind of things. Can't you remove complexity by generalizing the logic? Can the result used in your switch-case be passed as a parameter and used to trigger the numbers of c == X calls in the CandleXXX() methods?
This way you could remove the switch and lose a lot of complexity!
Edit
If you have further problems, consider creating a .NET Fiddle, I miss a lot of context in your code so I cannot efficiently help you here.
Some refactoring ideas for you:
// Somewhere else in your code, create a dictionary with your day1-day8 objects
var days = new Dictionary<int, Day>()
days[1] = day1;
...
days[8] = day8;
//Simplfiy your method
private void btnCandlesLight_Click(object sender, EventArgs e)
{
try
{
var dayIndex = Convert.ToInt32(textBox1.Text);
if(dayIndex > 0 && dayIndex <= 8)
{
days[dayIndex].Start(); //Get the corresponding day via its Key
LightUpCandles(dayIndex); //pass the key as a parameter
}
else
{
MessageBox.Show("Enter new day");
}
}
catch(InvalidCastException exception)
{
//Whatever you do when the textbox cannot be parsed
}
}
I still don't get what your candlesOne to five methods are really doing or why the method "candlesOne" lights up two candles (pay attention to the variable naming). I also don't get how this makes up some kind of timer... but here's a first potential refactoring for it anyway:
public void LightUpCandles(int dayIndex)
{
firedmatch.Left = firedmatch.Left + 100;
if(c == 1)
{
candle1.Visible = true;
}
if(c == 3 && dayIndex > 1)
{
candle2.Visible = true;
}
if(c == 5 && dayIndex > 2)
{
candle3.Visible = true;
}
if(c == 7 && dayIndex > 3)
{
candle4.Visible = true;
}
if(c == 11 && dayIndex > 4)
{
candle5.Visible = true;
}
}
Your switch logic is correct which I tested with the following;
int result;
result = Convert.ToInt32(textBox1.Text);
switch (result)
{
case 1:
MessageBox.Show("1");
break;
case 2:
MessageBox.Show("2");
break;
case 3:
MessageBox.Show("3");
break;
case 4:
MessageBox.Show("4");
break;
case 5:
MessageBox.Show("5");
break;
case 6:
MessageBox.Show("6");
break;
case 7:
MessageBox.Show("7");
break;
case 8:
MessageBox.Show("8");
break;
default:
MessageBox.Show("Enter new day");
break;
}
If you don't get the same results I would perhaps look at making the message boxes above display the data type of the variable.
MessageBox.Show(result.GetType().ToString());

Why won't my calculations for this code work?

private void btnCalculate_Click(object sender, RoutedEventArgs e)
{
double pay;
pay = 0.00;
double add;
add = 0.00;
int age;
age = int.Parse(txtAge.Text);
string month;
month = txtMonth.Text;
if (age >= 18 && age <= 55)
{
pay = 350;
}
else if (age <= 18)
{
pay = 150; //if-else-if statements depending on age
}
else if (age > 55)
{
pay = 35;
}
switch (month)
{
case "January":
case "january":
case "July":
case "july": //switch statement, how much you pay depending on month
add = 100;
break;
case "February":
case "february":
case "August":
case "august":
add = 120;
break;
case "March":
case "march":
case "September":
case "september":
add = 140;
break;
case "April":
case "april":
case "October":
case "october":
add = 160;
break;
case "May":
case "may":
case "November":
case "november":
add = 180;
break;
case "June":
case "june":
case "December":
case "december":
add = 120;
break;
}
lblTotal.Content = (pay + add) * 1.13; //calculation that prints to the label
}
So when I run the code it just outputs 0 in the label
If I put the Calculation at the bottom (seen here) it will say something about the label not being reachable. Any help would be great. Code has been solved
You can directly assign variables. Declaration and assignment need not be different statements.
18 has two different checks: >= 18 in the if, and <= 18 in the first else if. Not a code error but a semantics error.
The final assignment is inside the switch block and unreachable. Put it outside the switch.
It looks like you're using WPF? If so, you should have a look at the MVVM pattern, as well as data binding. It's a good bit to learn and not easy but very important in WPF. It will eliminate the need for querying and writing properties of elements in most cases, though – because that will be handled by the runtime.
Also consider using a ComboBox for the month. Way easier to validate the data.
As suggested your label assignment was inside the switch statement causing it not to execute unless the month was June or December.
In any case, I'd suggest though that you simplify.
Try this:
private void btnCalculate_Click(object sender, RoutedEventArgs e)
{
int age = int.Parse(txtAge.Text);
double pay = age <= 18 ? 150.0 : (age > 55 ? 35.0 : 350.0);
int index = (DateTime.Parse("1 " + txtMonth.Text).Month - 1) % 6;
double[] choices = new [] { 100.0, 120.0, 140.0, 160.0, 180.0, 120.0 };
double add = choices[index];
lblTotal.Content = (pay + add) * 1.13;
}
The label assignment was inside the switch statement. There's a lot of other improvements you can make to code as well.
For starters, you can also join assignment and declaration of variables and use .ToLower() in switch to save yourself the extra cases:
private void btnCalculate_Click(object sender, RoutedEventArgs e)
{
var pay = 0.00;
var add = 0.00;
var age = int.Parse(txtAge.Text);
var month = txtMonth.Text;
if (age >= 18 && age <= 55)
{
pay = 350;
}
else if (age <= 18)
{
pay = 150;
}
else if (age > 55)
{
pay = 35;
}
switch (month.ToLower())
{
case "january":
case "july":
add = 100;
break;
case "february":
case "august":
case "june":
case "december":
add = 120;
break;
case "march":
case "september":
add = 140;
break;
case "april":
case "october":
add = 160;
break;
case "may":
case "november":
add = 180;
break;
}
lblTotal.Text = Convert.ToString((pay + add) * 1.13); //calculation that prints to the label
}

image not displaying

I hope you can help me! I am trying to make a game similiar to candyland. I want the die to spin when the user clicks the button. A random number is chosen and based on that number, the dice displays the image for that number. That works! Then, I want our user to be able to move forward on our board- based on the spot that they're on, it adds whatever they spinned and the image on that spot becomes visible. When in debug mode, everything works perfectly but for some reason, the pawn never moves! Can you please tell me why. I am attaching my code below. Thank you so much!
protected void btnSpin_Click(object sender, EventArgs e)
{
Random randomNumber = new Random();
int x = randomNumber.Next(1, 6);
switch (x)
{
case 1:
//imgDie.ImageUrl = "~/Images/dice1.jpg";
Session["Die"] = "~/Images/dice1.jpg";
break;
case 2:
Session["Die"] = "~/Images/dice2.jpg";
break;
case 3:
Session["Die"] = "~/Images/dice3.jpg";
break;
case 4:
Session["Die"] = "~/Images/dice4.jpg";
break;
case 5:
Session["Die"] = "~/Images/dice5.jpg";
break;
case 6:
Session["Die"] = "~/Images/dice6.jpg";
break;
}
imgDie.ImageUrl = (string)Session["Die"];
place = place + x;
switch (place)
{
case 2:
img2.Visible = true;
img2.ImageUrl = (string)Session["Imagesrc"];
break;
case 3:
img3.Visible = true;
img3.ImageUrl = (string)Session["Imagesrc"];
break;
case 4:
img4.Visible = true;
img4.ImageUrl = (string)Session["Imagesrc"];
break;
case 5:
img5.Visible = true;
img5.ImageUrl = (string)Session["Imagesrc"];
break;
case 6:
img6.Visible = true;
img6.ImageUrl = (string)Session["Imagesrc"];
break;
case 7:
img7.Visible = true;
img7.ImageUrl = (string)Session["Imagesrc"];
break;
case 8:
img8.ImageUrl = (string)Session["Imagesrc"];
img8.Visible = true;
break;
my guess is your 'place' variable is a member field and it's being reinitialized with each page construction. chnge your place variable to be viewstate or session state like your other stuff.

Categories