all。这里的学生程序员,不仅仅是一个角落,但在数组方面很吃力。我有一项家庭作业,几周前我交了一半的分数,因为我无法让并行数组发挥作用。我们被要求创建一个GUI来计算六个不同区号的电话费用。GUI要求输入区号(您可以得到一个要键入的有效代码列表)和通话长度。我想我的问题是让程序在区域代码数组中循环,但我完全不知道该从哪里开始。(我还打赌,当我看到答案时,我会面面俱到。)这是我的GUI按钮代码。无论我输入什么区号,它都会返回1.40美元的费用。谢谢你的光临!
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");
}
}
试试这个
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
}
}
或者,如果你被分配了一个任务,你必须展示如何突破循环,那么你在当前代码中所需要的就是添加一个条件
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");
}