Java 程序在从 main() 中提取的变量之间输出 spaces,这很好。但是我想删除尾随 space

Java program is outputting spaces between variables pulled from main(), which is fine. However I would like to remove the trailing space

这是我的代码:

    import java.util.Scanner;

    public class LabProgram {

    public static double drivingCost(double drivenMiles, double dollarsPerGallon, double milesPerGallon)
    {  double totalCost = 0;
    totalCost = (drivenMiles / milesPerGallon) * dollarsPerGallon ;
    System.out.printf("%.2f", totalCost);
    System.out.print(" ");
    return totalCost;
    }
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    double milesPGallon;
    double dollarsPGallon;
    double driveMiles;
    double drivingCost;
    milesPGallon = input.nextDouble();
    dollarsPGallon = input.nextDouble();
    input.close();
    drivingCost(10, dollarsPGallon, milesPGallon);
    drivingCost(50, dollarsPGallon, milesPGallon);
    drivingCost(400, dollarsPGallon, milesPGallon);
    System.out.print("\r");
    }
    }

输出是:'1.58 7.90 63.20',我需要的是'1.58 7.90 63.20'。如何删除输出中的尾随 space?我曾尝试使用 trim() 和 replace() 两者都没有帮助。我是 Java 的新手,在过去一天半的时间里我一直在用头撞墙试图解决这个问题。任何帮助将不胜感激,即使它只是朝着正确方向的推动。先感谢您。

drivingCost 每次调用时都会打印 space:

public static double drivingCost(double drivenMiles, double dollarsPerGallon, double milesPerGallon)
{
    double totalCost = 0;
    totalCost = (drivenMiles / milesPerGallon) * dollarsPerGallon ;
    System.out.printf("%.2f", totalCost);
    System.out.print(" "); // <-------- here!
    return totalCost;
}

您可以删除该行,而是打印 space betweendrivingCost:

的调用
drivingCost(10, dollarsPGallon, milesPGallon);
System.out.print(" ");
drivingCost(50, dollarsPGallon, milesPGallon);
System.out.print(" ");
drivingCost(400, dollarsPGallon, milesPGallon);

或者,向 drivingCost 添加一个额外的参数:

public static double drivingCost(double drivenMiles, double dollarsPerGallon, double milesPerGallon, boolean isLastCall)
{
    double totalCost = 0;
    totalCost = (drivenMiles / milesPerGallon) * dollarsPerGallon ;
    System.out.printf("%.2f", totalCost);

    if (!isLastCall) {
        System.out.print(" ");
    }
    return totalCost;
}

并这样称呼它:

drivingCost(10, dollarsPGallon, milesPGallon, false);
drivingCost(50, dollarsPGallon, milesPGallon, false);
drivingCost(400, dollarsPGallon, milesPGallon, true);