Home > Mobile >  How to set a field in Java to 0 if the argument is negative?
How to set a field in Java to 0 if the argument is negative?

Time:10-21

I keep getting this error message,

The following code was executed:

 LemonadeStand ls = new LemonadeStand();
 ls.setLemons(1);
 ls.setLemons(-1);

ls.getLemons() should have returned 0, but it returned -1. Make sure setLemons sets the field to 0 if the argument is negative.

And I cannot seem to figure out what is wrong in my code, which is shown below. Thanks.

public void setLemons(int newLemons)
{
    if(lemons < 0)
    {
        lemons = 0; 
    }
    lemons = newLemons;
}

CodePudding user response:

OK Saul,

public void setLemons(int newLemons)
{
    if(newLemons < 0)
    {
        lemons = 0;

    } else {
        lemons = newLemons;
    }
}

Now,

LemonadeStand ls = new LemonadeStand();
ls.setLemons(1); // sets value to 1
ls.setLemons(-1); // sets value to 0;
  •  Tags:  
  • java
  • Related