I am currently working with storing data into arrays. The program takes the information from a text files and then formats the result with product name. The issues is that if other than a number(int) is found in the starting line of the text the file breaks. Specifically at productID = Convert.ToInt16(storeData[0]);. How can I avoid breaking the program if the first character in the text file is other than an integer?
how the info looks in the text file: ProductID, Month and Sales
1 5 20.00
CODE
string[] productName = new string[100];
string arrayLine;
int[] count = new int[100];
int productID = 0;
double individualSales = 0;
double[] totalSales = new double[100];
double[] totalAverage = new double[100];
productName[1] = "Cookies";
productName[2] = "Cake";
productName[3] = "Bread";
productName[4] = "Soda";
productName[5] = "Soup";
productName[99] = "Other";
while ((arrayLine = infile.ReadLine()) != null)
{
string[] storeData = arrayLine.Split(' ');
productID = Convert.ToInt16(storeData[0]);
individualSales = Convert.ToDouble(storeData[2]);
if (stateName[productID] != null)
{
count[productID] += 1;
totalSales[stateID] += individualSales;
}
else
{
count[99] += 1;
totalSales[99] += individualSales;
}
}
infile.Close();
Int16.TryParse
as Gromer stated, I’d rather use
int.TryParse(which is in factInt32.TryParse)…