Home > Software engineering >  is there any way i could do to be specific to my if else statements?
is there any way i could do to be specific to my if else statements?

Time:07-08

im a java newbie and can't seem to terminate my code wisely,here is my if else statement and what it does is just subtracts the other if statements,is there anyway i could do to subtract the availAmount to a specific if statement? thank you

double upgradeAccessories(double availAmount) 
{
    if(availAmount>21500)
    {
        hasAC=true;
        availAmount-=21500;
    }
    else 
    {
        hasAC=false;
    }
    
    if(availAmount>=14400) 
    {
        hasLeatherSeats=true;
    availAmount-=14400;
    }
    else
    {
        hasLeatherSeats=false;
    }
    
    if(availAmount>=6250) 
    {
        hasBackWipers=true;
    availAmount-=6250;
    }
    else 
    {
        hasBackWipers=false;
    }
    
    if(availAmount>=3300)
    {
        hasFogLights=true;
    availAmount-=3300;
    }
    else 
    {
        hasFogLights=false;
    }

    return availAmount;
}

CodePudding user response:

I think you want to do something like this:

if(availAmount>21500) {
    hasAC=true;
    availAmount-=21500;
}
else if(availAmount>=14400) 
{
        hasAC=false;
    hasLeatherSeats=true;
        availAmount-=14400;
}
else if(availAmount>=6250) 
{
        hasAC=false;
    hasLeatherSeats=false;
    hasBackWipers=true;
        availAmount-=6250;
}
else if(availAmount>=3300)
{
        hasAC=false;
    hasLeatherSeats=false;
    hasBackWipers=false;
    hasFogLights=true;
        availAmount-=3300;
}
else 
{
    hasFogLights=false;
}

You all are getting executed which is causing the problem. you can also use a switch statement which would be cleaner code.

CodePudding user response:

If you only want one if statement to run then you need to use the if (...) { ...} else if syntax. Changing your code so that the availAmount is only reduced once could be done with something like the following:

double upgradeAccessories(double availAmount) {
   
    hasAC = availAmount > 21500;
    hasLeatherSeats = availAmount >= 14400;
    hasBackWipers = availAmount >= 6250;
    hasFogLights = availAmount >= 3300;

    if(availAmount > 21500) {
        availAmount -= 21500;
    } else if(availAmount >= 14400) {
        availAmount -= 14400;
    } else if(availAmount >= 6250) {
        availAmount -= 6250;
    } else if (availAmount >= 3300) {
        availAmount -= 3300;
    }

    return availAmount;
}

Note that in the above I also directly used your conditions to set the 4 boolean variables at the very beginning of the method, so that this doesn't have to be done in the if..else block.

  • Related