I need help with this code. I need to do 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 for the matrix is not '[' or the ending character of the matrix is not ']'. For example, matrix = ] 1 2 3[ should be matrix = [1 2 3]
This is my code:
This is from my main in which I create the string and call the class method.
string text = "A = [8 5 5 4; 2 6 5 3; 8 5 2 6]"; this is my class:
public string[,] Matrix(string text)
{
try
{
try
{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(";")) { throw new Exception("Malformed separator'"); }if (text.Split(';')[0].Replace(" ", "").Length != text.Split(';')[1].Replace(" ", "").Length)
{ throw new Exception("unbalanced matrix"); }}catch (Exception a){Console.WriteLine(a.Message);}}
catch (Exception b){
Console.WriteLine(b.Message);
}
}
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;
}
I got the separator part to work, But I need help on number 1. I don't know if that code is correct.
carmelo anthonyPosted Nov 9, 2015, 12:44 AM
Nishant MittalPosted Nov 9, 2015, 12:37 AM
carmelo anthonyPosted Nov 9, 2015, 12:34 AM
Nishant MittalPosted Nov 9, 2015, 12:30 AM
carmelo anthonyPosted Nov 8, 2015, 11:57 PM
Nishant MittalPosted Nov 8, 2015, 11:40 PM
carmelo anthonyPosted Nov 8, 2015, 11:36 PM
Nishant MittalPosted Nov 8, 2015, 11:24 PM