首页 > 解决方案 > “简单”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”的节省但没有,我通过打印该行检查了所有值是否正确,但我不明白为什么它不会打印。

标签: javaif-statement

解决方案


发生这种情况是因为您正在检查packageRateA < packageRateC. 当你通过论点时,它不会得到满足。

hours=15.00当packageRateA 等于 packageRateC时, packageRateA 将为 19.95 。

如果您将条件更改为packageRateA <= packageRateC您的代码将起作用。


推荐阅读