using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//populate the troop number combo boxes
for (int i = 0; i < 240;i++) {
BarbNumcomboBox.Items.Add(i + 1);
}
}
private void calculateButton_Click(object sender, EventArgs e)
{
//Variables
int barbTrainingCost;
int barbTotal;
int numberOfBarbs = BarbNumcomboBox.SelectedIndex + 1;
//Find Cost of each barb
if (barbLvlComboBox.SelectedIndex == 0)
{
barbTrainingCost = 25;
}
else if(barbLvlComboBox.SelectedIndex == 1) {
barbTrainingCost = 40;
}
else if (barbLvlComboBox.SelectedIndex == 2) {
barbTrainingCost = 60;
}
else if (barbLvlComboBox.SelectedIndex ==3 )
{
barbTrainingCost = 100;
}
else if (barbLvlComboBox.SelectedIndex == 4)
{
barbTrainingCost = 150;
}
else if (barbLvlComboBox.SelectedIndex == 5)
{
barbTrainingCost = 200;
}
else if (barbLvlComboBox.SelectedIndex == 6)
{
barbTrainingCost = 250;
}
//calculate total cost for all barbs
barbTotal = numberOfBarbs * barbTrainingCost;
}
}
}
答案 0 :(得分:4)
你需要为barbTrainingCost变量赋值.... 如果你意识到,你正在宣布它,但从不在任何条件之外指定一个值....错误被抛出,因为你的条件都不是真的所以赋值永远不会发生......
首先,尝试声明你的变量的初始值为零...那么你应该解决为什么你的IF子句都没有达到真的....
int barbTrainingCost = 0;
答案 1 :(得分:1)
因为你总是将barbTrainingCost变量设置为if语句中的值(或者if),所以当你在计算中使用它时,它可以保持未分配状态。
您可以在创建变量时设置初始值(var barbTrainingCost = 1;),将最终的'else if'更改为else,或者使用默认值添加其他else语句。
作为单独的注释,因为您在比较中使用枚举,所以可以使用switch语句使您的代码更清晰。
switch (barbLvlComboBox.SelectedIndex)
{
case 0: barbTrainingCost = 25; break;
case 1: barbTrainingCost = 40; break;
default: barbTrainingCost = 123;
}