在 Java 中使用 printf 左对齐 [英] Left-aligning with printf in Java

查看:88
本文介绍了在 Java 中使用 printf 左对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I run the program, the factorial value right-aligns. Is there a way to make it left-justified while maintaining the 50 spaces in between?

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();  
        } 
    } 
}

推荐答案

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

According to the printf() specification the - symbol left-justifies output.

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

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

这篇关于在 Java 中使用 printf 左对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆