all. Student programmer here, more than a noob but struggling with arrays. I have a homework assignment that I turned in for half the points a few weeks ago because I couldn't get the parallel arrays to work. We were asked to create a GUI to calculate the cost of a phone call for six different area codes. The GUI asks for an area code (you get a list of valid codes to type in) and the length of the call. I think my problem is in getting the program to loop through the area code array, but I'm totally stumped as to where to go from here. (I also bet I'm going to facepalm when I see what the answer might be.) Here is my code for the GUI button. It returns a cost of $1.40 no matter what area code I enter. Thanks for looking!
private void calcButton_Click(object sender, EventArgs e)
{
int[] areaCode = { 262, 414, 608, 715, 815, 902 };
double[] rates = { 0.07, 0.10, 0.05, 0.16, 0.24, 0.14 };
int inputAC;
double total = 0;
for (int x = 0; x < areaCode.Length; ++x)
{
inputAC = Convert.ToInt32(areaCodeTextBox.Text);
total = Convert.ToInt32(callTimeTextBox.Text) * rates[x];
costResultsLabel.Text = "Your " + callTimeTextBox.Text + "-minute call to area code " + areaCodeTextBox.Text + " will cost " + total.ToString("C");
}
}
Try this
private void calcButton_Click(object sender, EventArgs e)
{
int[] areaCode = { 262, 414, 608, 715, 815, 902 };
double[] rates = { 0.07, 0.10, 0.05, 0.16, 0.24, 0.14 };
if(!string.IsNullOrEmpty(areaCodeTextBox.Text))
{
double total = 0;
if(!string.IsNullOrEmpty(callTimeTextBox.Text))
{
int index = Array.IndexOf(areaCode, int.Parse(areaCodeTextBox.Text)); //You can use TryParse to catch for invalid input
if(index > 0)
{
total = Convert.ToInt32(callTimeTextBox.Text) * rates[index];
costResultsLabel.Text = "Your " + callTimeTextBox.Text + "-minute call to area code " + areaCodeTextBox.Text + " will cost " + total.ToString("C");
}
else
{
//Message Area code not found
}
}
else
{
//Message Call time is empty
}
}
else
{
//Message Area Code is empty
}
}
Alternatively, if you are given an assignment where you have to show how to break out of a loop then all you need in your current code is an addition of a condition
private void calcButton_Click(object sender, EventArgs e)
{
int[] areaCode = { 262, 414, 608, 715, 815, 902 };
double[] rates = { 0.07, 0.10, 0.05, 0.16, 0.24, 0.14 };
int inputAC;
double total = 0;
for (int x = 0; x < areaCode.Length; ++x)
{
inputAC = Convert.ToInt32(areaCodeTextBox.Text);
total = Convert.ToInt32(callTimeTextBox.Text) * rates[x];
if(inputAC == areaCode[x]) //ADDED condition
break;
}
costResultsLabel.Text = "Your " + callTimeTextBox.Text + "-minute call to area code " + areaCodeTextBox.Text + " will cost " + total.ToString("C");
}