在我最近的任务中,我对这段代码有困难。这个任务向用户显示汽油的价格,询问他们想要什么类型的汽油和多少加仑。该程序以双精度形式返回总价。我已经在calculatePrice方法中创建了一个返回答案的开关。我在收集该信息并以某种方式将其打印到方法displayTotal时遇到了问题。此外,displayTotal必须是double。如有任何帮助,我们不胜感激。
public static double calculatePrice(int type, double gallons){
switch (type){
case 1:
System.out.printf("You owe: %.2f" , gallons * 2.19);
break;
case 2:
System.out.printf("You owe: %.2f", gallons * 2.49);
break;
case 3:
System.out.printf("You owe: %.2f", gallons * 2.71);
break;
case 4:
System.out.printf("You owe: %.2f", gallons * 2.99);
}
return type;
}
public static void displayTotal(double type){
System.out.println(type);
}
}发布于 2019-04-01 06:31:31
看起来像是一个简单的错误--您从calculatePrice返回的是type,而不是计算值:
return type;您需要的是计算结果并返回结果,而不是type。另外,如果你想先打印它,把它放到一个局部变量中会很有帮助。示例:
public static double calculatePrice(int type, double gallons) {
double result = 0;
switch (type) {
case 1:
result = gallons * 2.19;
break;
case 2:
result = gallons * 2.49;
break;
case 3:
result = gallons * 2.71;
break;
case 4:
result = gallons * 2.99;
}
System.out.printf("You owe: %.2f", result);
return result;
}发布于 2019-04-01 06:36:19
您需要将加仑和价格/加仑的乘法结果保存在一个变量中并返回它。
public static double calculatePrice(int type, double gallons){
switch (type) {
case 1:
return gallons * 2.19;
case 2:
return gallons * 2.49;
case 3:
return gallons * 2.71;
case 4:
return gallons * 2.99;
}
}
public static void displayTotal(double type, double gallons){
double totalPrice = calculatePrice(type, gallons);
System.out.printf("You owe: %.2f", totalPrice);
}https://stackoverflow.com/questions/55446003
复制相似问题