java - “简单”If 语句在一小段代码中不起作用 [初学者] [Java]
问题描述
我正在创建一种方法,让用户知道如果他们决定切换到另一个包会节省多少钱。
public static String savingsCalc(char pack, double hours)
{
String returnVal = "";
double packageRateA = 9.95;
double packageRateB = 13.95;
double packageRateC = 19.95;
double savings = 0;
if (hours > 10) packageRateA = 9.95 + ((hours - 10) * 2.00);
if (hours > 20) packageRateB = 13.95 + ((hours - 20) * 1.00);
if (pack == 'A')
{
if (packageRateA < packageRateB) returnVal = "";
else if (packageRateA < packageRateC && packageRateA > packageRateB)
{
savings = packageRateA - packageRateB;
System.out.printf("You would save $%.2f if you switched to package B!%n", savings);
}
else if (packageRateA > packageRateC)
{
savings = packageRateA - packageRateC;
System.out.printf("You would save $%.2f if you switched to package C!%n", savings);
}
}
return returnVal;
}//shows savings if changing to other package
如果我输入“15”小时,它应该打印“Package B”的节省但没有,我通过打印该行检查了所有值是否正确,但我不明白为什么它不会打印。
解决方案
发生这种情况是因为您正在检查packageRateA < packageRateC
. 当你通过论点时,它不会得到满足。
hours=15.00
当packageRateA 等于 packageRateC时, packageRateA 将为 19.95 。
如果您将条件更改为packageRateA <= packageRateC
您的代码将起作用。
推荐阅读
- python - 将同一天的所有数据收集到一行
- listview - 如何在主详细信息页面中添加导航页面?
- python - 创建具有 REAL 值(包括 UNIQUE 约束)的 SQLITE 表的最佳方法是什么?
- php - 未识别的索引错误,数据库中没有结果
- php - 从访问器返回 HTML 是否可以接受?
- gatsby - Gatsby 拒绝安装所有依赖项
- css - CSS动画悬停效果
- amazon-web-services - AWS fargate 中的 Auto-Scaling 策略之间的区别
- jquery - 从具有唯一 ID 的 DIV 中复制 href并将其粘贴到该 DIV 中的其他位置
- php - 尝试使用此代码在网页上上传图像,它不断给出错误