C# - 使用并行阵列来计算GUI中的电话费用

问题描述:

全部。这里的学生程序员不仅仅是一个noob,而是与阵列挣扎。我有一个家庭作业,几个星期前我已经交出了一半的积分,因为我无法使平行阵列工作。我们被要求创建一个GUI来计算六个不同区号的电话费用。图形用户界面要求输入区号(您将获得要输入的有效代码列表)以及通话的长度。我认为我的问题在于让程序循环遍历区号阵列,但我完全被困在了从这里开始的地方。 (我也打赌,当我看到答案时,我会去facepalm。)这是我的GUI按钮代码。不管我输入什么区号,它都会返回1.40美元的成本。感谢您的期待!C# - 使用并行阵列来计算GUI中的电话费用

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"); 


     } 
    } 
+0

如果你需要一个区号的结果你为什么要在区号上循环? – progrAmmar

+0

您需要在'areaCode'数组中找到'inputAC'的索引。 –

+0

@progrAmmar,很棒的一点。我现在看到我错误地表达了我的问题。我的意思是说我在索引区域码数组时遇到了麻烦。 –

试试这个

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"); 
} 
+0

谢谢。添加条件/中断到我当前的代码,它的工作。现在正在处理错误消息组合,因为这似乎是一种练习TryParse等的好方法。 –