【问题标题】:How to you use the space and sign flags when formatting an integer?格式化整数时如何使用空格和符号标志?
【发布时间】:2016-09-24 22:04:54
【问题描述】:

对于这个代码

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 条语句中工作正常,但在第 4 条语句中抛出异常?
  3. 对于第二个语句,为什么( 标志会覆盖+ 标志的效果?为什么不是反过来?

【问题讨论】:

    标签: java formatting


    【解决方案1】:

    您明确引用的javadoc 说:

    如果同时给出'+'' ' 标志,则将抛出IllegalFormatFlagsException

    它还列出了以下限制,不适用于您的示例:

    如果同时给出'-''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 = '+ ('
    

    如您所见,'+'' ' 互斥是有道理的。它们都定义了正数符号的显示方式。

    【讨论】:

      猜你喜欢
      • 2019-12-17
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 2016-10-03
      • 2021-11-04
      • 1970-01-01
      相关资源
      最近更新 更多