Reputation: 63
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
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
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
Reputation: 6527
Can made in one line as,
public int getGasCapacity(){
return (currentGas <= GAS_CAP ? (GAS_CAP - currentGas) : 0 );
}
Upvotes: 0