Hi Everyone,
I have this:
[code]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace VendingMachineApp
{
public partial class Form1 : Form
{
VendorMachine vendorMachine;
public String[] snacks = { "Cookie", "Bubble gum", "Prefzels", "Soda" };
string line = "has been dispended";
int choose;
int i;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] snacks = new string[4];
snacks[0] = "Cookie";
snacks[1] = "gum";
snacks[2] = "Prefzels";
snacks[3] = "soda";
switch (snacks[choose])
{
case snacks[0] :txtOutput.Text = snacks[0] + line;
break;
case snacks[1]: txtOutput.Text = snacks[1] + line;
break;
case snacks[2]: txtOutput.Text = snacks[2] + line;
break;
case snacks[3]: txtOutput.Text = snacks[3] + line;
break;
default:
break;
}//end swicth
}
}
}
[/code]
but what has to be for the case? case snacks[1] - then I get an error: "A constant value is expected".
I just want if user put an 1 in a textbox that u get as outcome: "gum" and for 2 - outcome: "prefzels".
THX
Loading
VulpesPosted Nov 8, 2011, 4:58 PM
You need to insert this line before you enter the switch statement:
int.TryParse(txtChoose.Text, out choose);
If an invalid number is entered in the textbox, then 0 will be used instead.
To make sure that choose is within bounds, you could also add these lines:
if (choose < 0)
choose = 0;
else if (choose > 3)
choose = 3;
albert albertPosted Nov 8, 2011, 5:14 PM
albert albertPosted Nov 8, 2011, 4:47 PM
I had that , but then the problem is that only the first line: cookie is shown.For example if u put a 2 in the textbox and press the button u still get cookie back and not Prefzels:
switch (choose)
{
case 0 :txtOutput.Text = snacks[0] + " " + line;
break;
case 1: txtOutput.Text = snacks[1] + " " + line;
break;
case 2: txtOutput.Text = snacks[2] + " "+ line;
break;
case 3: txtOutput.Text = snacks[3] + " " +line;
break;
default:
break;
}//end swicth
also for this: txtOutput.Text = snacks[choose];
VulpesPosted Nov 8, 2011, 4:40 PM