我想知道如何從if語句中獲取計算值並將該值用於其他內容。這是我的代碼只是一部分,我需要幫助的部分:如何獲取if語句中計算的值並在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;
然而,當我嘗試使用它從第一,如果在第二份聲明,如果聲明reducedTax = taxedIncome - ((1000 * reductionFactor1) + (500 * reductionFactor2));
,它給我的錯誤納稅收入計算值:
variable taxedIncome might have not been initialized
所以我的問題是,我怎麼能從第一個if語句中得到這個計算出來的值,並在第二個語句中使用呢?
提示:當代碼不進入'if'發生了什麼? –
@BoristheSpider我明白你的意思了。如果用戶輸入的值不符合if語句的條件,我應該做一個else語句。所以我所做的就是在另一個聲明中使'taxedIncome = income'。 –