使用 printf 舍入到小数点后两位时出现 java.util.IllegalFormatPrecisionException 错误

标签 java

我是一名新的 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/

相关文章:

java - 如何导出 Google Storage 中 Cloud SQL 数据库的备份?

java - 如何在 Java 中执行字符串中的代码

java - Android 中是否有某种#define 可用于简化语句?

java - 在线程 "main"java.lang.NoClassDefFoundError : 中获取异常

java - 无法为非实体集合创建元素连接

从文件读取时出现 java.util.InputMismatchException

java - SimpledateFormat的parse方法java

java - 无法从浏览器打开文档文件

java - 在 Java 中创建两个线程

java - mvn site 命令不起作用 - 生成 css 和图像而不是 html