JayLo
JayLo

Reputation: 63

how to use if-else statement in accessor?

this is part of my program. I have to be sure that the amount of gas does not exceed the top gas capacity. I do not know how to write the else part? I ask the user to enter the current gas and it should be less or equal 30.

    private final int GAS_CAP = 30 

    public int getGasCapacity(int gasCapacity)
    {
       if(currentGas <= GAS_CAP)
       {
         gasCapacity = GAS_CAP - currentGas;
       }
       else gasCapacity = currentGas;
       return gasCapacity;
   }

Upvotes: 2

Views: 253

Answers (3)

Tetramputechture
Tetramputechture

Reputation: 2921

private final int GAS_CAP = 30 

public int getGasCapacity()
{
   int gasCapacity;
   if(currentGas <= GAS_CAP)
   {
     gasCapacity = GAS_CAP - currentGas;
   } else {
     gasCapacity = 0;
   }
   return gasCapacity;
}

Your else statement was wrong, and there shouldn't be a parameter. You could also easily accomplish this with one line, but I'm not sure if you know how to use ternary syntax.

Upvotes: 1

Kevin Avignon
Kevin Avignon

Reputation: 2903

First thing, you should make your question a little more clear because I don't really understand what you're trying to do. I'm going to write you what I think you're trying to achieve and you tell me if it's okay or comment what was wrong in the answer.

private final GAZ_LIMIT = 30;


public int ObserveGazCapacity(int gazCapacity)
{

 if(gazCapacity<=GAZ_LIMIT)
 {
   gazCapacity-=GAZ_LIMIT;
 }else{
    gazCapacity=0; //in case higher than limit, capacity will be at the maximum value permitted 
}
 return gazCapacity;

}

Hopes that what you're looking for !

Upvotes: 0

Rakesh KR
Rakesh KR

Reputation: 6527

Can made in one line as,

public int getGasCapacity(){
   return (currentGas <= GAS_CAP ? (GAS_CAP - currentGas) : 0 );
}

Upvotes: 0

Related Questions