gpt4 book ai didi

java - 使用 printf() 时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 06:41:48 24 4
gpt4 key购买 nike

这是我到目前为止的代码。

import java.util.Scanner;
public class two {

public static void main(String[] args) {
System.out.println("--- Stage 1 Taxi Fare Calculator ---");

Scanner user_input = new Scanner( System.in );

System.out.print("Enter in pick up time: ");
System.out.flush();
String startTime = user_input.next();

System.out.print("Enter in pickup point: ");
System.out.flush();
String pickUp = user_input.next();

System.out.print("Enter in drop off point: ");
System.out.flush();
String dropOff = user_input.next();

System.out.print("Enter in trip distance in km: ");
System.out.flush();
Double tripDist = user_input.nextDouble();
user_input.nextLine();

Double fareRate = 1.60;
Double baseFare = tripDist * fareRate;
Double totalFare = baseFare;

String m1 = "The pickup point was: %15s%n";
String m2 = "The drop off point was: %13s%n";
String m3 = "The pickup time was: %11s%n";
String m4 = "Estimated distance (km): %12f%n";
String m5 = "Fare Charged: $%11.2f%n";
String m6 = "Base fare: $%15.2f%n";
String m7 = "Total fare: $%14.2f%n";
String m8 = "Plus surcharges: $%14.2f%n";
System.out.println(" --- Taxi fare details --- ");
System.out.printf(m1, pickUp);
System.out.printf(m2, dropOff);
System.out.printf(m3, startTime);
System.out.printf(m4, tripDist);
System.out.printf(m5, fareRate);
System.out.printf(m6, baseFare);
System.out.printf(m7, totalFare);
}


}

编辑2(最终):我已经在我的代码中添加了更多内容,现在已经得到了您在上面看到的内容,现在我需要做的就是添加附加费,所以当它在特定时间时,它是一定的成本,也是区域的附加费,无论如何不寻求帮助,只是让你们知道你们已经提供了很多帮助,我谢谢你们。顺便说一句,如果我不应该尽可能多地编辑此内容,我深表歉意。

最佳答案

如果您在读取变量的同一行声明变量,您的代码可能会更短,并且如果您不使用 println(),则应该 flush(),即

System.out.print("Enter in pick up time:  ");
System.out.flush();
String startTime = user_input.next();

System.out.print("Enter in pickup point: ");
System.out.flush();
String pickUp = user_input.next();

System.out.print("Enter in drop off point: ");
System.out.flush();
String dropOff = user_input.next();

System.out.print("Enter in trip distance in km: ");
System.out.flush();
Double tripDist = user_input.nextDouble();
user_input.nextLine();

然后,您需要在格式中包含输出类型String(s),

String m1 = "The pickup point was: %s%n"; // %n or \n - both are newline
String m2 = "The drop off point was: %s%n";
String m3 = "The pickup time was: %s%n";
String m4 = "Estimated distance (km): %f%n";
String m5 = "Fare Charged: $%.2f%n";
String m6 = "Base fare: $%.2f%n";
String m7 = "Total fare: $%.2f%n";

接下来,当您调用 printf() 时,您应该传递参数,而不是连接 -

System.out.printf(m1, pickUp);
System.out.printf(m2, dropOff);
System.out.printf(m3, startTime);
System.out.printf(m4, tripDist);
System.out.printf(m5, fareRate);
System.out.printf(m6, baseFare);
System.out.printf(m7, totalFare);

然后我认为它会按照您的预期工作。

关于java - 使用 printf() 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24592186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com