Java 为什么当我尝试获取两到两个小数位时会出现这个错误

Java 为什么当我尝试获取两到两个小数位时会出现这个错误,java,Java,我正在创建一个简单的程序来计算运行汽车的成本。程序运行得很好,但我想看看是否能得到小数点后2位的最终答案。我试着使用'%8.2f'这个东西,但是它说找不到println(string,double)的方法 这是我的代码: /* Program to calculate the running cost of car */ import java.util.Scanner; public class RunningCosts { public static void main(Stri

我正在创建一个简单的程序来计算运行汽车的成本。程序运行得很好,但我想看看是否能得到小数点后2位的最终答案。我试着使用
'%8.2f'
这个东西,但是它说
找不到println(string,double)的方法

这是我的代码:

/* Program to calculate the running cost of car */

import java.util.Scanner;

public class RunningCosts {
    public static void main(String[] args) {

        final int TOTAL_DISTANCE = 100000;

        Scanner in = new Scanner(System.in);

        System.out.print("Enter the car cost: ");
        double carCost = in.nextDouble();
        System.out.print("Enter the service cost: ");
        double serviceCost = in.nextDouble();
        System.out.print("Enter the service interval: ");
        double serviceInterval = in.nextDouble();
        System.out.print("Enter km per litre: ");
        double kmPerLitre = in.nextDouble();
        System.out.print("Enter the fuel cost per litre: ");
        double fuelCostPerLitre = in.nextDouble();


        double serviceTotal = (TOTAL_DISTANCE/serviceInterval) * serviceCost;
        System.out.println( "Service Total: " + serviceTotal); //Here

        double fuelCost = (TOTAL_DISTANCE/kmPerLitre) * fuelCostPerLitre;
        System.out.println( "Fuel Cost: " + fuelCost); //Here

        double totalCost = carCost + fuelCost + serviceTotal;

        System.out.println( "Estimated Cost: " + totalCost); //And here
    }
}

注释行是我希望格式化为2位小数的行,可以使用
@shmosel
建议的
printf
,也可以使用
String.format

System.out.println( "Service Total: " + String.format("%.2f", serviceTotal));

有关更多用法示例,请参见。

使用
printf()
而不是
println()
。除了@shmosel的注释外,请记下并正确缩进代码谢谢!实际上我还没有被教过如何正确缩进,但我会继续学习it@Nicole然后使用IDE。它们可以帮助你正确地缩进代码,也可以自动格式化写得不好的代码。