我正在编写一种基于总薪酬和家属人数计算所得税的方法。当我尝试编译以下代码时,我的dTaxOnIncome变量未初始化。
public static double incomeTax(double gross, int dependents)
{
double dTaxOnIncome; // holds the calculated income tax.
if(gross >= 10000 && dependents == 0)
{
dTaxOnIncome = gross * .25;
}
else
{
if((gross >= 10000) && ((dependents >= 1 && dependents <= 4)))
{
if(dependents == 1)
{
dTaxOnIncome = gross * .24;
}
else
{
if(dependents == 2)
{
dTaxOnIncome = gross * .23;
}
else
{
if(dependents == 3)
{
dTaxOnIncome = gross * .22;
}
else
{
if(dependents == 4)
{
dTaxOnIncome = gross * .21;
}
else
{
if(dependents == 5)
{
dTaxOnIncome = gross * .205;
}
else
{
if(dependents == 6)
{
dTaxOnIncome = gross * .20;
}
else
{
if(dependents > 6)
{
dTaxOnIncome = gross * .18;
}
else
{
}
}
}
}
}
}
}
}
}
return dTaxOnIncome;
}// end incomeTax (double, int)
我知道我可以使用if else语句,但我已经尝试过多种方式解决这个问题,这似乎是最直接的。
答案 0 :(得分:2)
Java中的局部变量需要在使用之前进行隐式初始化。在您的代码中,您没有事先初始化变量dTaxOnIncome,因此java会尝试查看您是否稍后对其进行初始化,但事实证明您的变量未在某些位置初始化,因此Java正在考虑这些情况。在那些执行的情况下,访问该值是一个问题。
您可以在声明中添加一些默认值
这将使您的代码工作,如果您不想创建默认值,那么无论您的程序采用何种执行路径,都要确保您的变量已初始化。
答案 1 :(得分:0)
public static double incomeTax(double gross, int dependents){
double dTaxOnIncome=0.0;
// if gross is less than 10000 there is no tax deduction
if(gross<10000) return dTaxOnIncome;
//gross is larger or equal to 10000
//calculate tax deduction according to number of depedents
if(dependents==0){
dTaxOnIncome = gross * .25;
}
if(dependents==1){
dTaxOnIncome = gross * .24;
}
if(dependents==2){
dTaxOnIncome = gross * .23;
}
if(dependents==3){
dTaxOnIncome = gross * .22;
}
if(dependents==4){
dTaxOnIncome = gross * .21;
}
if(dependents==5){
dTaxOnIncome = gross * .205;
}
if(dependents==6){
dTaxOnIncome = gross * .20;
}
if(dependents>6){
dTaxOnIncome = gross * .18;
}
return dTaxOnIncome;
}