我试图找出为什么在输出小数时%.2f
声明在我的代码中不起作用,我检查了其他类似的问题,但我似乎无法在特定问题中找到问题我收到的逻辑错误。当我编译我的程序它编译得很好,我去运行它,一切都输出正常,直到我得到最终的成本,我试图只显示小数点后2位的十进制值。
我在主题“main”
中遇到异常Java.util.illegalformatconversionexception f! = Java.lang.string
At java.util.Formatter$formatspecifier.failconversion(Unknown Source)
At java.util.Formatter$formatspecifier.printFloat(Unknown Source)
At java.util.Formatter.format(Unknown Source)
At java.io.printstream.format(Unknown Source)
At java.io.printstream.printf(Unknown Source)
At Cars.main(Cars.java:27)
这是我的代码:
import java.util.Scanner;
public class Cars
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int carYear, currentYear, carAge;
double costOfCar, salesTaxRate;
double totalCost;
String carModel;
System.out.println("Please enter your favorite car model.");
carModel = input.nextLine();
System.out.println("Please enter the year of the car");
carYear = input.nextInt();
System.out.println("Please enter the current year.");
currentYear = input.nextInt();
carAge = currentYear - carYear;
System.out.println("How much does the car cost?");
costOfCar = input.nextDouble();
System.out.println("What is the sales tax rate?");
salesTaxRate = input.nextDouble();
totalCost = (costOfCar + (costOfCar * salesTaxRate));
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f",totalCost + " " + " dollars.");
}
}
我不确定是什么导致了这个问题。
答案 0 :(得分:1)
尝试:
System.out.printf("The model of your favorite car is %s, the car is %d years old, the total of the car is %.2f dollars.", carModel, carAge, totalCost);
或者更具可读性:
System.out.printf("The model of your favorite car is %s," +
" the car is %d years old," +
" the total of the car is %.2f dollars.",
carModel, carAge, totalCost);
答案 1 :(得分:1)
这是因为%.2f
被该方法调用中的整个第二个参数替换。问题是通过在f
中指定%.2f
,您说第二个参数是float或double。在这种情况下,第二个参数是totalCost + " " + " dollars."
,它计算为字符串。
要解决此问题,您需要将第二个参数设为float或double。这可以通过将+ " " + " dollars."
从第二个参数的末尾移动到第一个参数的结尾来实现,如下所示:
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f" + " " + " dollars.",totalCost);
您还可以从该行中删除许多不必要的连接,从而产生以下结果:
System.out.printf("The model of your favorite car is" + carModel + ", the car is " + carAge + " years old, the total of the car is %.2f dollars.", totalCost);
答案 2 :(得分:0)
变量必须作为System.out.printf()函数的参数。 "%。2f"将被作为第二个参数传递的double值替换。
例如:
System.out.printf("The value is %.2f", value);
对于其他变量类型和多个变量也是如此,
String str = "The value is: ";
double value = .568;
System.out.printf("%s %.2f", str, value);
这将输出:"值为:.57"