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 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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With