Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left-aligning with printf in Java

Tags:

java

printf

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();  
        } 
    } 
}
like image 902
Blimeo Avatar asked Feb 25 '13 20:02

Blimeo


People also ask

How do I left justify with printf?

printf allows formatting with width specifiers. For example, printf( "%-30s %s\n", "Starting initialization...", "Ok." ); You would use a negative width specifier to indicate left-justification because the default is to use right-justification.

How do you left align in Java?

There are a variety of ways to format data in Java. [alignment] not needed for right alignment. Include (-) for left alignment. format() behaves similar to print() in that it will leave you on the same line, and will not move down to the next line.

What does %n do in Java printf?

In C printf(), %n is a special format specifier which instead of printing something causes printf() to load the variable pointed by the corresponding argument with a value equal to the number of characters that have been printed by printf() before the occurrence of %n.


1 Answers

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

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

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

like image 198
Hunter McMillen Avatar answered Sep 23 '22 16:09

Hunter McMillen