2013-07-14 34 views
-1

這是表應該如何看起來像:對齊號碼錶

enter image description here

我的表產生正確的輸出。只需要對齊水平面上的值。

import java.util.Scanner; 

公共類tesy

{ 公共靜態無效的主要(字串[] args)

{ 
    Scanner keyboard = new Scanner (System.in); 

    int rows=0, cols=0; 
    int a, b; 

    System.out.print("Enter number of rows from 1-10"); 


    rows = keyboard.nextInt(); 

    System.out.print("Enter number of columns from 1-10"); 

    cols = keyboard.nextInt(); 

    for (int c=1; c<=cols; c++){ 
     System.out.print(" "+c); 

    } 
    System.out.println(); 
    System.out.println( "----------------------"); 

    for (int d=1; d<=rows;d++){ 
     System.out.print(""+d); 
     System.out.println(); 

    } 

    for (a=1; a<=rows; a++) 
    { 

     for (b=1; b<=cols; b++) 
     { 


      System.out.print(" "+a*b); 
     } 
     System.out.println(); 


    } 
} 

}

+5

你真的需要了解循環,尤其是[for循環(http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html )。另外[這個例子](http://stackoverflow.com/a/15215434/1393766)可能會讓你感興趣。 – Pshemo

+0

同意上面的評論,你還需要看看http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html –

+0

是的,我更新了我的代碼,但仍然有水平問題側。 – colors

回答

0

當表時,你絕對,肯定不能靠只是空格和\ t(製表符的轉義字符)。這些被認爲是無用的方式,因爲它們可以根據程序中額外的信息而改變。

我建議學習如何使用的printf()

System.out.printf(); 

這就是在幾乎任何處理表和具體定位信息situtaion使用。

System.out.printf() training

0

最簡單和最有效的方式做到填充(左或右)是使用String.format()方法。

左墊8位:

String.format("% 8d", yournumber);