【问题标题】:Java: System.out.format IllegalFormatPrecision ExceptionJava:System.out.format IllegalFormatPrecision 异常
【发布时间】:2016-02-15 18:48:43
【问题描述】:

考虑以下循环来打印图表: 假设数组中的所有元素以及感兴趣的元素都有一个赋值,为什么 for 循环(确切地说是 System.out.format)会产生 IllegalFormatPrecisionException?

   double[] sbalance; 
   double[] fbalance; 
   double[] interest; 
   sbalance = new double[months]; 
   fbalance = new double[months]; 
   interest = new double[months];  
   int deposit; 
    for (int q = 1; q <= months; q++)
   {
       System.out.format ("%18.2d%", sbalance[q-1]); 
       System.out.format ("%18.2d%", interest [q-1]); 
       System.out.format ("%18.2d%", (double)deposit);
       System.out.format ("%18.2d%", fbalance [q-1]); 
    }

即使我返回并将我的数组重新声明为 Double[] 而不是 double[],程序也会产生相同的错误(我意识到 java 在自动装箱方面不一致)

非常感谢任何帮助。

【问题讨论】:

    标签: java formatting number-formatting


    【解决方案1】:

    有两个问题。

    1. 在格式字符串中,%18.2d应该是%18.2f
    2. 在格式字符串的末尾,% 应该是%n。 (在 cron 文件中,% 表示换行符,但在 Java 中,%n 表示换行符。)

    这是工作代码:

    public class Interest {
    
      public static void main(String[] args) {
        int months = 12;
        int deposit = 1000;
    
        double[] sbalance; 
        double[] fbalance; 
        double[] interest; 
        sbalance = new double[months]; 
        fbalance = new double[months]; 
        interest = new double[months];  
        for (int q = 1; q <= months; q++) {
          System.out.format ("Month %d%n", q); 
          System.out.format ("%18.2f%n", sbalance[q-1]); 
          System.out.format ("%18.2f%n", interest [q-1]); 
          System.out.format ("%18.2f%n", (double)deposit);
          System.out.format ("%18.2f%n", fbalance [q-1]); 
        }
    
      }
    
    }
    

    如果您想在编译时被警告 IllegalFormatPrecision 错误而不是遭受运行时崩溃,您可以使用 Checker FrameworkFormat String Checker。如果你已经安装并运行了

    $CHECKERFRAMEWORK/checker/bin/javac -processor formatter Interest.java
    

    那么编译器会警告您有关特定错误消息的问题。

    【讨论】:

      【解决方案2】:

      使用%f 代替%d

      前者格式化浮点数;后者格式化整数。要求打印带 2 个小数位的整数是没有意义的。

      【讨论】:

      • 欢迎来到俱乐部。你赢了!
      【解决方案3】:

      格式中的d 表示十进制整数,而不是双精度数。你应该使用f

      【讨论】:

        猜你喜欢
        • 2016-01-26
        • 2016-09-11
        • 2021-12-05
        • 2012-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多