日期:2014-05-20 浏览次数:21008 次
public class MultiTest {
    public static void main(String[] args) {
        System.out.println(" MultiTest Table ");
        System.out.println("---------------------");
        showTable1();
    }
    static void showTable1() {
        System.out.print("  ");
        for (int i = 1; i < 10; i++)
            System.out.print(i + "  ");
        System.out.println();
        for (int i = 1; i < 10; i++) {
            System.out.print(i + " ");
            for (int j = 1; j < 10; j++)
                System.out.print(i * j + (i * j > 9 ? " " : "  "));
            System.out.println();
        }
    }
}
------解决方案--------------------
PS:对于格式化输出效果,用格式化输出函数System.out.printf(System.out.format)要比System.out.print容易得多:
public class MultiTest {
    public static void main(String[] args) {
        System.out.println(" MultiTest Table ");
        System.out.println("---------------------");
        // showTable1();
        showTable2();
    }
    static void showTable1() {
        System.out.print("  ");
        for (int i = 1; i < 10; i++)
            System.out.print(i + "  ");
        System.out.println();
        for (int i = 1; i < 10; i++) {
            System.out.print(i + " ");
            for (int j = 1; j < 10; j++)
                System.out.print(i * j + (i * j > 9 ? " " : "  "));
            System.out.println();
        }
    }
    static void showTable2() {
        System.out.print("  ");
        for (int i = 1; i < 10; i++)
            System.out.printf("%-3d", i);
        System.out.println();
        for (int i = 1; i < 10; i++) {
            System.out.printf("%-2d", i);
            for (int j = 1; j < 10; j++)
                System.out.printf("%-3d", i * j);
            System.out.println();
        }
    }
}