Java: return 2D Array with very varying entry lengths as formatted string

Viewed 824

I want to write a toString method for a Matrix class where I need to return a formatted string which contains the matrix. The entries in the matrix are very different in length so just separating the entries with a TAB doesn't the trick. Right now I have the following:

public String toString(){
    String str = "";
    for(int i=0;i < _dim[0];i++){
        for(int j=0;j < _dim[1];j++){
            str += this.values[i][j] + "\t" + "\t";
        }
        str += "\n";
    }
    return str;
}

Which gives me something like this.

3.2004951E7     -1.591328E7     17839.0     
-35882.0        17841.0     -20.0       
1794.0  -892.0         1.0

Is there a way to print these properly aligned without knowing in advance how long each entry is going to be?

Thanks.

2 Answers
Related