2015-03-21 3 views
0

Как вы печатаете двумерный массив в тонком формате?Распечатка 2d Массив в формате матрицы java

Я хочу напечатать матрицу, как показано ниже, с макс 4 места для чисел и максимум 2 пространств для дробных чисел например XXXX.XX

double A[][]= { 
    { 3.152 ,96.1 , 77.12}, 
    { 608.12358 , -5.15412456453 , -36.1}, 
    { -753..555555, 6000.156564 , -155.541654} 
}; 

//I need this output 
    3.15 | 96.10 | 77.12 
608.12 | -5.15 | -36.10 
-753.55 | 6000.15 | -155.54 
+4

Читайте о [System.out.printf] (http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#printf%28java .lang.String,% 20java.lang.Object ...% 29). – RealSkeptic

ответ

1

Это может помочь

public static void main(String[] args) { 
    double A[][]= { 
      { 3.152 ,96.1 , 77.12}, 
      { 608.12358 , -5.15412456453 , -36.1}, 
      { -753.555555, 6000.156564 , -155.541654} 
     }; 
    //Number of characters in format , here XXXX.XX length is 7 
    int numberFormatLength=7; 
    //Iterating through Array 
    for(int i=0;i<A.length;i++){ 
     for(int j=0;j<A.length;j++){ 
      //Calculating number of spaces required. 
      int spacesRequired=numberFormatLength-String.format("%.2f",A[i][j]).length(); 
      //Creating calculated number of spaces 
      String spaces = new String(new char[spacesRequired]).replace('\0', ' '); 
      //formatting element to the format with decimal place 2 
      String arrayElement=String.format("%.2f",A[i][j]); 
      //Using ternary operator to calculate what to print for every third Element in your array 
      System.out.print((j/2==1)?(spaces+arrayElement+"\n"):(spaces+arrayElement+"|")); 
     } 

    } 


} 
2

Вот один подход:

// Convert to String[][] 
int cols = A[0].length; 
String[][] cells = new String[A.length][]; 
for (int row = 0; row < A.length; row++) { 
    cells[row] = new String[cols]; 
    for (int col = 0; col < cols; col++) 
     cells[row][col] = String.format("%.2f", A[row][col]); 
} 

// Compute widths 
int[] widths = new int[cols]; 
for (int row = 0; row < A.length; row++) { 
    for (int col = 0; col < cols; col++) 
     widths[col] = Math.max(widths[col], cells[row][col].length()); 
} 

// Print 
for (int row = 0; row < A.length; row++) { 
    for (int col = 0; col < cols; col++) 
     System.out.printf("%" + widths[col] + "s%s", 
          cells[row][col], 
          col == cols - 1 ? "\n" : " | "); 
} 

Результат:

3.15 | 96.10 | 77.12 
608.12 | -5.15 | -36.10 
-753.56 | 6000.16 | -155.54 
Смежные вопросы