仍然是 Java 新手,我的任务是为一个纸男孩制作利润计算器,但是我收到了这个错误:

Enter the number of daily papers delivered: 50
Enter the number of Sunday papers delivered: 35
The amount collected for daily papers was: Exception in thread "main" java.util
IllegalFormatConversionException: d != java.lang.Double
    at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
    at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
    at java.util.Formatter$FormatSpecifier.print(Unknown Source)
    at java.util.Formatter.format(Unknown Source)
    at java.io.PrintStream.format(Unknown Source)
    at java.io.PrintStream.printf(Unknown Source)
    at lab2b_MontelWhite.main(lab2b_MontelWhite.java:24)

这是我到目前为止所拥有的:
//Paper Boy's Wages Calculator

import java.util.Scanner;
public abstract class lab2b
{
public static void main(String[] args)
{
        Scanner input = new Scanner( System.in);
        int x;
        int y;
        int result;

        System.out.print("Enter the number of daily papers delivered: ");
        x = input.nextInt();

        System.out.print("Enter the number of Sunday papers delivered: ");
        y = input.nextInt();
        double dailyResult = x * .3;

        System.out.printf("The amount collected for daily papers was: %d\n",
        dailyResult);
        int SundayResult = y * 1;

        System.out.printf("The amount collected for Sunday papers was: %d\n",

        SundayResult);
        double totalResult = dailyResult + SundayResult;

        System.out.printf("The total amount of money collected was: %d\n",

        totalResult);
        double ProfitResult = (SundayResult + dailyResult)/2;

        System.out.printf("The paper boy's profit is: %d\n", ProfitResult);
}
}

我究竟做错了什么?
我添加了 double ,我更改了“结果”的名称。我只是不确定我做错了什么。

最佳答案

您可以查看 Formatter javadocs 以查看所有数据类型格式字母。

从该页面开始,%d 将数字格式化为“十进制整数”。这可能是让你感到困惑的地方。这实际上意味着“以 10 为基数的整数”,例如使用 (30)10 表示二进制数 (11110)2。在转换类型中要查看的重要事项是参数类别。该列中的“整数”表示没有小数部分的整数数据类型,例如 intlongBigInteger 。另一方面,“浮点”表示带有小数部分,例如 doublefloatBigDecimal 。在您的情况下,您需要 %f

您还可以指定精度,即数字小数部分中显示的位数。由于您使用的是金钱,我将展示一个使用美元的示例:

System.out.printf("The amount collected for Sunday papers was: $%.2f\n",
    SundayResult);

这将打印如下内容:
The amount collected for Sunday papers was: $65.33

代替:
The amount collected for Sunday papers was: $65.333333333

资源:
  • Formatter javadocs
  • Java Trail
  • Similar SO question
  • 关于java - 利润计算器接收错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18431377/

    10-09 04:40