我是一名新的 Java 编码员,在使用 printf
将值四舍五入到两位小数时遇到错误。谁能帮助我理解错误的原因以及如何解决该错误?
代码
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
int age = 0;
int count = 0;
int round = 0;
while ((age < 12) || (age > 18))
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a non-teen age: ");
age = input.nextInt();
if ((age < 12) || (age > 18))
{
count = count + 1;
round = round + age;
}
}
System.out.println("Opps! " + age + " is a teen's age.");
System.out.println("Number of non-teens entered: " + count);
System.out.printf("Average of non-teens ages entered: %.2d", round);
}
}
错误:
Exception in thread "main" java.util.IllegalFormatPrecisionException: 2 at java.util.Formatter$FormatSpecifier.checkInteger(Unknown Source) at java.util.Formatter$FormatSpecifier.<init>(Unknown Source) at java.util.Formatter.parse(Unknown Source) at java.util.Formatter.format(Unknown Source) at java.io.PrintStream.format(Unknown Source) at java.io.PrintStream.printf(Unknown Source) Demo.main(Demo.java:31)
最佳答案
我猜错误就在这一行
System.out.printf("Average of non-teens ages entered: %.2d", round);
'.2' 对于十进制整数没有意义。删除它:
System.out.printf("Average of non-teens ages entered: %d", round);
关于使用 printf 舍入到小数点后两位时出现 java.util.IllegalFormatPrecisionException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42741044/