public override string ToString() {
string matrixView = "";
for (int r=0; r<=this.rows; r ) {
for (int c=0; c<=this.columns; c ) {
}
}
return matrixView;
}
Note:
##################################
this.rows
= row number
this.columns
= column number
this.matrix
= 2-dimensional array used as data store
##################################
In this code, I aim to make seem for example 4x4 matrix like:
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
Each newline must be started with "[". Values(this.columns
times) and spaces(this.columns
-1 times) must be printed. Finally, the line must be ended with "]\n"
And these operations above must be done this.rows
times.
I think in this way. But nested loops always make me confuse. So, I tried several times but I couldn't be successful at it. And String.Concat
threw NullReferenceException
when I tried to concaten matrixView
with "[", "]\n" and this.matrix[r, c].ToString()
.
CodePudding user response:
I think you are looking for something like this:
public override string ToString() {
// When building string, better use StringBuilder instead of String
StringBuilder matrixView = new StringBuilder();
// Note r < matrix.GetLength(0), matrix is zero based [0..this.rows - 1]
// When printing array, let's query this array - GetLength(0)
for (int r = 0; r < matrix.GetLength(0); r ) {
// Starting new row we should add row delimiter
if (r > 0)
matrixView.AppendLine();
// New line starts from [
matrixView.Append("[");
// Note r < matrix.GetLength(1), matrix is zero based [0..this.rows - 1]
for (int c = 0; c < matrix.GetLength(1); c ) {
// Starting new column we should add column delimiter
if (c > 0)
matrixView.Append(' ');
matrixView.Append(matrix[r, c]);
}
// New line ends with [
matrixView.Append("]");
}
return matrixView.ToString();
}
CodePudding user response:
You could for example do something like:
for (int r=0; r<=this.rows; r ) {
var s = "[";
for (int c=0; c<=this.columns; c ) {
s = myValue.ToString() " ";
}
s = "]";
Console.WriteLine(s);
}
But if you numbers are larger than 9 you might want to pad the numbers with spaces. It is not very efficient to do many small concatenations like this. But unless you do this very frequently it will not matter.