2016-01-08 78 views
0

我必須以矩陣的方式打印出表格,每個數字格式化爲4的寬度(這些數字是右對齊的,並去掉每行上的前導/尾隨空格)。第一3行看起來像:如何從整數行中刪除前導/尾隨空格?

1 2 3 4 5 6 7 8 9 10 11 12 
2 4 6 8 10 12 14 16 18 20 22 24 
3 6 9 12 15 18 21 24 27 30 33 36 

這是我的代碼:

public static void main (String[] args) { 
    int i,j; 
    for(i=1;i<=3;i++){ 
     for(j=1;j<=12;j++){ 
      System.out.format("%4d",i*j); 
     } 
     System.out.println(); 
    } 
} 

在輸出第一個整數得到由3 spaces.How移位,以汽提出在每個前/後間隔線?

+0

代碼看起來像Java,但請指定你的問題,你所使用的語言。 – DrunkenPope

回答

0

嘗試打印第一個數字相同,因爲我從你的第二循環,並從第二即2開始你的第二個循環,如:

for(i=1;i<=3;i++){ 
    System.out.print(i); 
    for(j=2;j<=12;j++){ 
     System.out.format("%4d",i*j); 
    } 
    System.out.println(); 
} 
+0

但如果第一個循環將被限制爲10而不是3,那麼這些數字將不再對齊...... – xmoex

+0

它會..爲什麼不是@xmoex? – SMA

+0

其實這個問題是在一個競爭性的編程站點中給出的。我嘗試提交與您相同的代碼,但它通過了局部。這是一個簡單的問題,仍然讓我發瘋。還有其他建議值得讚賞 – Tannia

0

如果允許把你的情況是這樣 INT I,J ;

for (i = 1; i <= 3; i++) 
     { 
      for (j = 1; j <= 12; j++) 
      { 
       if (j == 1) 
       { 
        System.out.format("%d", i * j); 
       } 
       else 
       { 
        System.out.format("%4d", i * j); 
       } 
      } 
      System.out.println(); 
     } 
1

假設你想擺脫之間的所有無用空格,爲什麼不避免它們擺在首位?

public static void main(String[] args) { 
    int rows = 3, columns = 12; 

    for (int i = 1; i <= rows; i++) { 
     for (int j = 1; j <= columns; j++) { 
      // figure out the max # of digits needed 
      int necessaryDigits; 
      if (rows * j < 10) { 
       necessaryDigits = 1; 
      } else if (rows * j < 100) { 
       necessaryDigits = 2; 
      } else if (rows * j < 1000) { 
       necessaryDigits = 3; 
      } else { 
       necessaryDigits = 4; 
      } 
      // print them accordingly with one extra space to distinguish 
      // the numbers and avoid the leading one in 1st column 
      System.out.format("%" + (necessaryDigits + (j == 1 ? 0 : 1)) 
        + "d", i * j); 
     } 
     System.out.println(); 
    } 
} 

輸出:

1 2 3 4 5 6 7 8 9 10 11 12 
2 4 6 8 10 12 14 16 18 20 22 24 
3 6 9 12 15 18 21 24 27 30 33 36 

輸出或10行:

1 2 3 4 5 6 7 8 9 10 11 12 
2 4 6 8 10 12 14 16 18 20 22 24 
3 6 9 12 15 18 21 24 27 30 33 36 
4 8 12 16 20 24 28 32 36 40 44 48 
5 10 15 20 25 30 35 40 45 50 55 60 
6 12 18 24 30 36 42 48 54 60 66 72 
7 14 21 28 35 42 49 56 63 70 77 84 
8 16 24 32 40 48 56 64 72 80 88 96 
9 18 27 36 45 54 63 72 81 90 99 108 
10 20 30 40 50 60 70 80 90 100 110 120 
+0

謝謝,我用你的想法做了一點不同,根據問題和結果。 – Tannia

相關問題