Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading