Reputation: 4000
For this code
public static void main(String[] args) {
System.out.println(String.format("%+(d", 14));
System.out.println(String.format("%+(d", -14));
System.out.println(String.format("% (d", 14));
System.out.println(String.format("%+ (d", -14));
}
The output is
+14
(14)
14
[An exception is thrown]
According to this page, as the Flags section describes, I can use the +
, (i.e. space) and
(
signs\flags to format integers as shown in the code above.
My questions are:
space
flag work fine for the 3rd statement but throws an exception for the 4th ?(
flag override the effect of the +
flag ? Why isn't it the other way around ?Upvotes: 0
Views: 621
Reputation: 159106
The javadoc you referenced explicitly says:
If both the
'+'
and' '
flags are given then anIllegalFormatFlagsException
will be thrown.
It also lists the following restrictionm, which doesn't apply to your example:
If both the
'-'
and'0'
flags are given then anIllegalFormatFlagsException
will be thrown.
If you want to see the effect of the various flags, here is a little test program:
public static void main(String[] args) {
test("%d");
test("%+d");
test("% d");
test("%(d");
test("%+ d");
test("%+(d");
test("% (d");
test("%+ (d");
}
private static void test(String fmt) {
try {
System.out.printf("%5s: '" + fmt + "'%n", fmt, 14);
System.out.printf("%5s: '" + fmt + "'%n", fmt, -14);
} catch (Exception e) {
System.out.printf("%5s: %s%n", fmt, e);
}
}
Output
%d: '14'
%d: '-14'
%+d: '+14'
%+d: '-14'
% d: ' 14'
% d: '-14'
%(d: '14'
%(d: '(14)'
%+ d: java.util.IllegalFormatFlagsException: Flags = '+ '
%+(d: '+14'
%+(d: '(14)'
% (d: ' 14'
% (d: '(14)'
%+ (d: java.util.IllegalFormatFlagsException: Flags = '+ ('
As you can see, it makes sense that '+'
and ' '
are mutually exclusive. They both define how the sign of a positive number should be displayed.
Upvotes: 2