I just learned about exception handling. So, I am still getting use to it. I know how to do the basic exception handling like entering in a correct value for division and having it throw a DividebyZeroException if a incorrect value is entered.
But I need help some help on doing the following:
Create an exception handling to throw an error if:
1) The number of integer in each row are not equal to each other for example: Matrix = [ 3 4; 9 8 1] should be: matrix = [ 3 4 2; 9 8 1]
2) the semicolon ";" that I use as a separator is replace by an invalid character such as: matrix = [ 3 4 2 # 9 8 1]
3) The starting character of the matrix is not '[' or the ending character is not ']': for example A = ] 1 2 3[ should be A = [1 2 3]
This is my code:
This is from my "main" in which I create the string. The string is called into the method in the class "Matrix".
string text = "A = [8 5 5 4; 2 6 5 3; 8 5 2 6]";
this is my class
public string[,] Matrix(string text)
{
char[] splitOne = { '[', ']' };
char[] splitTwo = { ';' };
char[] splitThree = { ' ' };
words = text.Split(splitOne)[1]
.Split(splitTwo, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(splitThree, StringSplitOptions.RemoveEmptyEntries))
.ToArray();
if (!text.Contains(";"))
{
Console.WriteLine("malformed seperator");
return null;
}
if (text.Split(';')[0].Replace(" ", "").Length != text.Split(';')[1].Replace(" ", "").Length)
{
Console.WriteLine("unbalanced matrix");
return null;
}
string[,] matrix = new string[words.Length, words[0].Length];
for (int i = 0; i < words.Length; ++i)
{
for (int j = 0; j < words[i].Length; ++j)
{
matrix[i, j] = words[i][j];
}
}
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write("{0} ", matrix[i, j]);
}
Console.WriteLine();
}
return matrix;
}
How would I make these exceptions work. Right now, the separator works fine. But I can't get this part to work:
1) The number of integer in each row are not equal to each other for example: Matrix = [ 3 4; 9 8 1] should be: matrix = [ 3 4 2; 9 8 1]
it keeps showing my error message even when the matrix is balance.
I also need help on:
3) The starting character of the matrix is not '[' or the ending character is not ']': for example A = ] 1 2 3[ should be A = [1 2 3]
Aucun commentaire:
Enregistrer un commentaire