-2
文字列はnullとして初期化され続けます...または少なくともそのように見えます。私は私の行列のカスタムtoString関数を作成しようとしています。 this.matrixArray
は、次元「m x n」の2次元配列です。文字列はnullで初期化され続けます
public String toString() {
String stringAsMatrix = "";
String dimensions = this.m + "," + this.n + "\n";
stringAsMatrix += dimensions;
String[] dataRows = new String[this.m];
for (int row = 0; row < this.m; row++) {
for (int column = 0; column < this.n; column++) {
String elementString = "";
elementString += this.matrixArray[row][column];
if (column == this.n-1) {
dataRows[row] += elementString + "\n";
} else {
dataRows[row] += elementString + ","; // Only add a comma if this isn't the last element in the row
}
}
stringAsMatrix += dataRows[row];
}
return stringAsMatrix;
}
これは出力ですが、なぜ文字列の前に 'null'が表示されるのか理解できません。次元は正しいです(行列の配列は実際2x2です)。自体も(my matrix is {{1,2}, {3,4}})
2,2
null1.0,2.0
null3.0,4.0
「新しい文字列[this.m]」を作成すると、ヌルがいっぱいになります。非プリミティブ型の配列と同じです。 – user2357112
また、ループ内で '+ ='を使用して文字列を構築することは、実際には非効率的な方法です。 – user2357112
@ user2357112 '+ ='は実際に 'StringBuilder'を使うようコンパイルします。これは' javap -c Classname'で見られるように、効率的です。 –