Java: returns a 2D array with very different input lengths as a formatted string

I want to write a method toStringfor the Matrix class where I need to return a formatted string containing a matrix. The entries in the matrix are very different in length, so simply separating the entries with the help is TABnot a trick. 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 correctly aligned without knowing in advance how long each record will be?

Thanks.

+4
source share
2 answers

Is there a way to print these correctly aligned without knowing in indicate how long each record will be?

, , . , , : %-xs:

  • : maxWidth[col], : .
  • 2D-,
  • , "%-"+maxWidth[col]+"s ", - % .
  • . .

:

   String data[][] = {{3.2004951E7+"" , -1.591328E7+"",  17839.0+"" },
                      {-35882.0 +"" , -17841.0+"",  -20.0+"" }};


    int col = data[0].length;
    int row = data.length;

    int maxWidth[] = new int[col];

    for(String[] rowD : data)
     for(int i=0; i< col; i++)
     {
         if(maxWidth[i] < rowD[i].length())
             maxWidth[i] = rowD[i].length();
     }

    String format = "";

    for(int x : maxWidth)
        format += "%-"+(x+2)+"s ";

    format +="%n";

    System.err.println(format);

    for(String[] rowD : data)
    {
        System.out.printf(format, rowD);
    }

:

3.2004951E7   -1.591328E7   17839.0   
-35882.0      -17841.0      -20.0  
+2

String.format(), , maxLength.

public String toString(){
  String str = "";
  for(int i=0;i < _dim[0];i++){
      for(int j=0;j < _dim[1];j++){
        String value = String.valueOf(this.values[i][j]);
        str += String.format("%1$-" + (max-value.length()) + "s", " ") + value + "\t";
      }
    str += "\n";
  }
  return str;
}
+1

All Articles