Java 利润计算器的接收错误?
对Java还是新手,我的任务是为一个纸童制作利润计算器,但我收到了以下错误:Java 利润计算器的接收错误?,java,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
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);
}
}
我做错了什么?
我添加了双打,我更改了“结果”的名称。我只是不确定我做错了什么。
%d
是一个十进制整数。双打时使用%f
您可以在的文档中阅读格式字符串语法。应该是-
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);
您可以查看javadocs以查看所有数据类型格式字母
从该页面,%d
将数字格式化为“十进制整数”。这可能就是让你困惑的地方。这实际上意味着“以10为基数的整数”,比如用(30)10表示二进制数(11110)2。在转换类型中要注意的重要事项是参数类别。该列中的“整数”表示不含小数部分的整数数据类型,如int
、long
和biginger
。另一方面,“浮点”是指带有小数部分,如double
、float
和BigDecimal
。在您的情况下,您需要%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
资源:
%d
代表整数……我讨厌只能选择一个答案。两人都很有帮助。