2016-09-24 50 views
0

对于这个代码如何在格式化整数时使用空格和符号标志?

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

输出是

+14 
(14) 
14 
[An exception is thrown] 

根据this page,作为标志部分描述,我可以使用+(即空间)和(迹象\标志如上面的代码所示来格式化整数。

我的问题是:

  1. 凡指出如何这些标志互相交流?
  2. 为什么space标志对第三条语句正常工作,但是会为第四条语句引发异常?
  3. 对于第二条语句,为什么(标志会覆盖+标志的效果?为什么不是相反呢?

回答

2

javadoc你明确提到说:

如果给出的'+'' '标志都被那么IllegalFormatFlagsException将被抛出。

它还列出了以下restrictionm,这并不适用于你的例子:如果给出'-''0'标志都那么IllegalFormatFlagsException将被抛出

如果你想看到的各种标志的作用,这里是一个小的测试程序:

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

输出

%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 = '+ (' 

正如你所看到的,这是有道理的'+'' '是互斥的。它们都定义了如何显示正数的符号。

相关问题