2017-02-13 131 views
-2

我的字符串不斷初始化爲null ...或者至少看起來像這樣。我想爲我的矩陣做一個自定義的toString函數。 this.matrixArray是尺寸'm x n'的二維數組。字符串不斷初始化爲空

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'。尺寸是正確的(矩陣數組的確是2×2)。這些值本身也是正確的(my matrix is {{1,2}, {3,4}})

2,2 
null1.0,2.0 
null3.0,4.0 
+0

當你做一個'新的字符串[this.m]',它開始充滿了空值。與任何非原始類型的數組相同。 – user2357112

+0

另外,在循環中用'+ ='構建字符串是一種非常低效的方式。 – user2357112

+0

@ user2357112'+ ='實際上編譯爲使用'StringBuilder',這在後臺有效,可以用'javap -c Classname'看到。 –

回答

1
dataRows[row] += elementString + "\n"; 

dataRows[row]開始了與它null。所以它變成

dataRows[row] = null + elementString + "\n" 

......這正是你所得到的。相反,寫

dataRows[row] = elementString + "\n"; 
+0

我很愚蠢。非常感謝您的幫助。 –