2016-10-01 71 views
0

我需要做一個乘法表,顯示1 * 1到12 * 12。我有這個工作,但它需要在13列的格式,看起來像下面的圖表,真的很感激任何幫助。乘法表與2d陣列

1 2 3 4 5 6 7 8 9 10 11 12 

1 1 2 3 4 5 ... 

2 2 4 6 8 10 .... 

3 

4 

5 

6 

... 

到目前爲止的代碼:

public class timetable { 

    public static void main(String[] args) { 

     int[][] table = new int[12][12]; 

      for (int row=0; row<12; row++){ 
       for (int col=0; col<12; col++){ 
       table[row][col] = (row+1) * (col+1); 
       } 
      } 

      for (int row = 0; row < table.length; row++) { 
       for (int col = 0; col < table[row].length; col++) { 
        System.out.printf("%6d", table[row][col]); 
       } 
       System.out.println(); 
      } 

    } 

} 

回答

1

打印表格之前打印的列標題,並在每個行的開始打印行標題。您可以使用下面的代碼。

int[][] table = new int[12][12]; 

for (int row=0; row<12; row++){ 
    for (int col=0; col<12; col++){ 
    table[row][col] = (row+1) * (col+1); 
    } 
} 

// Print column headings 
System.out.printf("%6s", ""); 
for (int col = 0; col < table[0].length; col++) { 
    System.out.printf("%6d", col+1); 
} 
System.out.println(); 

for (int row = 0; row < table.length; row++) { 
    // Print row headings 
    System.out.printf("%6d", row+1); 

    for (int col = 0; col < table[row].length; col++) { 
     System.out.printf("%6d", table[row][col]); 
    } 
    System.out.println(); 
}