Learn AP Comp Sci

Problem of the Day

Monday, October 21, 2024


Problem:

The CookieJar class is an abstraction of a cookie jar that holds a number of cookies, numCookies, all of the same type, cookieName. A partial listing of the class description is given here.

public class CookieJar
{
private String cookieName;
private int numCookies;

/* constructor and some methods not shown */

/**
* The eatCookie method reduces the number of cookies in
* the jar by 1, if there are still cookies in the jar.
* Additionally, an error code is returned with a value
* of 0 if the cookie was successfully eaten, or -1
* if a cookie couldn't be eaten.
* @return 0 if cookie eaten, -1 if eating a cookie failed
*/
public int eatCookie()
{ /* code not shown */ }
}

Which code below could successfully be used for the eatCookie method?


  1. if (numCookies > 1)
    numCookies--;
    return 0;
    else
    return -1;

  2. if (numCookies >= 0)
    {
    numCookies--;
    return 0;
    }
    else
    {
    return -1;
    }

  3. if (numCookies > 0)
    {
    return 0;
    numCookies--;
    }
    else
    {
    return -1;
    }

  4. if (numCookies > 0)
    {
    numCookies--;
    return 0;
    }
    else
    {
    return -1;
    }

Show solution:

The correct answer is d. The other choices include errors of one type or another. Choice (a) needs curly braces { } around the if-clause—a compiler will throw an "else without if" error here. Choice (b) has an off-by-one error, with an empty cookie jar allowing one more cookie to be eaten. And choice (c) returns the successful error code 0 before removing the cookie from the jar.