Reputation: 6116
I am trying to produce right aligned numbers looking a bit like this:
12345
2345
but I clearly does not understand the syntax. I have been trying to follow these instructions. and Come up with the following attempt (it is integers so d and I want width 7 and 0 decimals):
public class test {
public static void main( String[] args ) {
System.out.format("%7.0d%n", 12345);
System.out.format("%7.0d%n", 2345);
}
}
but no matter what I do I seem to end up with IllegalFormatPrecisionException
. Is there a way to do this using this tool? If not how else would you do it?
Upvotes: 1
Views: 4815
Reputation: 1
converter %d is for integers and %f is for float. "%7.0d%n" is used with a float(i.e., as %7.0f%n) and "%7d%n" is used for integer representation.this is the reason for IllegalFormatPrecisionException exception.
Reference link http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Upvotes: 0
Reputation: 30151
From the linked page, it shows this:
System.out.format("%,8d%n", n); // --> " 461,012"
You can omit the comma, and change the 8 to a 7
Upvotes: 1
Reputation: 117587
Do it like this:
public class test {
public static void main( String[] args ) {
System.out.format("%7d%n", 12345);
System.out.format("%7d%n", 2345);
}
}
Upvotes: 1
Reputation: 33171
You can do something like this:
public class Test {
public static void main( String[] args ) {
System.out.format("%7d%n", 12345);
System.out.format("%7d%n", 2345);
}
}
Essentially this code asks Java to pad the string with spaces so that the output is exactly 7 characters.
Upvotes: 3