Can someone please tell me what I'm missing, the class reads values from a text file and should store them for other use, I can see the values with
Console.Write(eachCell[0])
but I can't save the values. I've tried using
string[]
and List<string>
but no luck. It should store the values being read to a list or array but so far it is not. Nothing shows on the console.
class test
{
public void tryOut()
{
#region file.read
try
{
string fileLocation = @"shelfInfo.txt";
List<string> cells = File.ReadAllLines(fileLocation).ToList();
aray(cells);
}
catch
{
new FileNotFoundException();
}
#endregion
}
public void aray(List<string> cells)
{
string[] t = new string[20];
string[] k = new string[20];
string a = "", b = "", c = "", d = "";
int i = 0;
foreach (string cell in cells)
{
string[] eachCell = cell.Split('@', '\t', '\n');
a = t[0] = eachCell[0].ToString(); //Consol.Write on eachCell directly shows the right values.
b = t[1] = eachCell[1].ToString();
c = t[2] = eachCell[2].ToString();
d = t[3] = eachCell[3].ToString();
for (; i < eachCell.Length; i++)
{
k[i] = a; //should store the values from eachCell
}
}
Console.Write(" " + a + " " + b + " " + " " + c + " " + d); //means the value are being receivedbut no stored
}
}
// contents of text file
//A11[1]@ A12[0]@ A13[1]@ A14[1]@
//A21[1]@ A21[1]@ A23[0]@ A24[0]@
//A31[1]@ A32[0]@ A33[1]@ A34[1]@
//A41[1]@ A41[1]@ A43[0]@ A44[0]@
I'd also, appreciate any tips on exception handling.
Your program doesn't return anything because you use the following code.
catch { new FileNotFoundException(); }
Console.Write
return nothing just because the exception is caught but it doesn't throw a new exception. There is an exception because eachCell
doesn't contain 4 elements and you try to access the element. In fact, you don't have to do the try-catch
unless you want to handle this exception manually. If the file isn't there, a FileNotFoundException
would already be thrown automatically. Change the tryOut
method as the following.
public void tryOut()
{
#region file.read
var fileLocation = @"Path";
aray(File.ReadAllLines(fileLocation).ToList());
#endregion
}
public static void aray(List<string> cells)
{
List<string> t = new List<string>();
foreach (string cell in cells)
{
string[] eachCell = cell.Split('@', '\t');
foreach (var e in eachCell)
{
t.Add(e);
}
}
foreach (var e in t)
{
Console.WriteLine(e);
}
}