[英]Java: System.out.format IllegalFormatPrecision Exception
Consider the following loop to print a chart: Assuming that all elements in the array as well as interest have an assigned value, why would the for loop (the System.out.format, to be exact) yield an IllegalFormatPrecisionException?考虑以下循环来打印图表:假设数组中的所有元素以及感兴趣的元素都具有指定的值,为什么 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]);
}
Even if I go back and redeclare my arrays as Double[] instead of double[], the program yields the same error (I realise that java is inconsistent about autoboxing)即使我返回并将我的数组重新声明为 Double[] 而不是 double[],该程序也会产生相同的错误(我意识到 java 与自动装箱不一致)
Any help is much appreciated.任何帮助深表感谢。
Use %f
instead of %d
.使用%f
而不是%d
。
The former formats floating point numbers;前者格式化浮点数; the latter formats integers.后者格式化整数。 It makes no sense to ask to print an integer with 2 decimal places.要求打印带有 2 个小数位的整数是没有意义的。
There are two problems.有两个问题。
%18.2d
should be %18.2f
.在格式字符串中, %18.2d
应该是%18.2f
。%
should be %n
.在格式字符串的末尾, %
应该是%n
。 (In cron files, %
means newline, but in Java, %n
means newline.) (在 cron 文件中, %
表示换行,但在 Java 中, %n
表示换行。)Here is working code:这是工作代码:
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]);
}
}
}
If you want to be warned of IllegalFormatPrecision errors at compile time rather than suffering a run-time crash, you can use the Format String Checker of the Checker Framework .如果您想在编译时收到 IllegalFormatPrecision 错误的警告而不是运行时崩溃,您可以使用Checker Framework的格式字符串检查器。 If you had installed it and run如果你已经安装并运行
$CHECKERFRAMEWORK/checker/bin/javac -processor formatter Interest.java
then the compiler would have warned you about your problems with specific error messages.那么编译器会警告您有关特定错误消息的问题。
The d
in the format means decimal integer, not a double.格式中的d
表示十进制整数,而不是双精度数。 You should use a f
.您应该使用f
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.