考虑以下循环来打印图表: 假设数组中的所有元素以及兴趣元素都有一个指定值,为什么 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 在自动装箱方面不一致)
非常感谢任何帮助。
最佳答案
有两个问题。
- 在格式字符串中,
%18.2d
应为%18.2f
。 - 格式字符串末尾的
%
应为%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 错误警告而不是遭受运行时崩溃,您可以使用 Format String Checker Checker Framework的。如果您已安装并运行
$CHECKERFRAMEWORK/checker/bin/javac -processor formatter Interest.java
那么编译器会通过特定的错误消息警告您有关问题的信息。
关于Java:System.out.format IllegalFormatPrecision 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35416866/