如何获取在 if 语句中计算的值并在 if 语句之外使用它?

How can I take a value calculated in a if statement and use it outside the if statement?

我想知道如何从 if 语句中获取计算值并将该值用于其他用途。这只是我的代码的一部分,我需要帮助的部分:

    double taxedIncome;
    double reducedTax;
    int reductionFactor1 = numberSchool;
    int reductionFactor2 = numberChildren - numberSchool;

    if (income == 10000 && housingCosts > 8000 || income < 10000) {
        taxedIncome = income * 0.18;
    }

    if (housingCosts < 6000 && numberChildren >= 2 && numberSchool >= 1) {
        reducedTax = taxedIncome - ((1000 * reductionFactor1) + (500 * reductionFactor2));
        System.out.println(reducedTax);
    }

正如您在第一个 if 语句中看到的,它表示如果收入(用户输入的值)等于 10000 且住房成本(也是用户输入的)大于 8000,或者如果收入小于大于10000,则收入乘以0.18。

taxedIncome = income * 0.18;

但是,当我尝试在第二个 if 语句 reducedTax = taxedIncome - ((1000 * reductionFactor1) + (500 * reductionFactor2)); 中使用第一个 if 语句的征税收入的计算值时,它给出了错误:

variable taxedIncome might have not been initialized

所以我的问题是,如何从第一个 if 语句中获取计算值并在第二个 if 语句中使用它?

有多种方法可以做到这一点:

  • if前计算保存,if中复用

  • 计算方法也可以被 if

  • 调用
  • 使用赋值returns一个值

但是,您遇到的问题具体是并非所有路径在使用前都会初始化 taxedIncome

你是在告诉计算机,如果某种情况为真,那么taxedIncome = income * 0.18;它在问,"ok, so what should it be if it's not?"

如果答案不完全相同,请考虑在您的第一个 if 中添加一个 else。如果您要在此处设置默认值,请考虑在开始时将 taxedIncome 设置为默认值。

最好在声明变量时对其进行初始化。通常,您希望将数字初始化为零。

在您的情况下,您的 if 语句可能无法执行,因此 taxedIncome 可能从未被赋值

    double taxedIncome = 0; // Initialize to zero or some default value
    double reducedTax = 0; // Initialize to zero or some default value
    int reductionFactor1 = numberSchool;
    int reductionFactor2 = numberChildren - numberSchool;

    if (income == 10000 && housingCosts > 8000 || income < 10000) {
        taxedIncome = income * 0.18;
    } else {
        // If you initialized taxedIncome to zero you may want to default it to some other value if you if statement results in false.
        // taxedIncome = ???
    }

    if (housingCosts < 6000 && numberChildren >= 2 && numberSchool >= 1) {
        reducedTax = taxedIncome - ((1000 * reductionFactor1) + (500 * reductionFactor2));
        System.out.println(reducedTax);
    }