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
}
因此,当我运行代码时,它只在标签中输出0 如果我将计算放在底部(见此处),它会说一些关于标签无法访问的内容。任何帮助都会很棒。代码已经解决
答案 0 :(得分:3)
看起来您正在使用WPF?如果是这样,您应该查看MVVM模式以及数据绑定。在WPF中学习并不容易但非常重要。但是,在大多数情况下,它将不再需要查询和编写元素的属性 - 因为它将由运行时处理。
还要考虑在本月使用ComboBox。更容易验证数据。
答案 1 :(得分:2)
根据建议,您的标签分配在switch
声明中,导致它不会执行,除非月份是6月或12月。
无论如何,我建议你简化。
试试这个:
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;
}
答案 2 :(得分:0)
标签分配在switch语句中。您还可以对代码进行许多其他改进。
对于初学者,您还可以加入变量的赋值和声明,并在switch中使用.ToLower()来节省额外的情况:
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
}