14

当我运行程序时,阶乘值右对齐。有没有办法让它左对齐,同时保持中间的 50 个空格?

public class Exercise_5_13
{
    public static void main( String[] args )
    {
        int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9,
                          10, 11, 12, 13, 14, 15, 16,
                          17, 18, 19, 20 };

        long factorial = 0;

        try
        {
            System.out.print("\n\n");
            System.out.printf("%s%50s\n", "Integer", "factorial");

            for ( int number : numbers )
            {
                System.out.printf( "%4d", number);
                factorial = (long)1;

                for(int i=1; i <= number; i++)
                    factorial = factorial * (long)i;

                System.out.printf("%50.0f\n",(double)factorial);
            } 

            System.out.print("\n\n");
        } 
        catch (Exception e)
        {
            e.printStackTrace();  
        } 
    } 
}
4

1 回答 1

26

根据printf()规范,-符号左对齐输出。

System.out.printf("%-50.0f\n",(double)factorial);

来源: http ://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

于 2013-02-25T20:31:08.487 回答