在 Java 中与 printf 左对齐

2022-09-04 00:46:49

当我运行程序时,阶乘值右对齐。有没有办法让它左对齐,同时保持中间的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();  
        } 
    } 
}

答案 1

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

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

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


答案 2