收益计算器的错误?

时间:2013-08-25 16:52:28

标签: java

还是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);
}
}

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

3 个答案:

答案 0 :(得分:6)

%d是十进制整数。使用%f表示双打。

您可以在Formatter的文档中了解格式字符串语法。

答案 1 :(得分:3)

应该是 -

System.out.printf("The amount collected for daily papers was: %f\n", dailyResult);
System.out.printf("The total amount of money collected was: %f\n",  totalResult);
System.out.printf("The paper boy's profit is: %f\n", ProfitResult);

因为%f表示双精度数,%d表示整数。如果你想要两个小数点,你可以做 -

String.format("%.2f", ProfitResult);

<强> Oracle tutorial.

答案 2 :(得分:3)

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

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

您也可以指定精度,这是数字小数部分显示的位数。由于您正在使用资金,我将使用USD显示一个示例:

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

资源: