Practice Questions: Using an API (Reference)
Consider the Plane class below:
public class Plane
{
//returns true only if there is an enemy immediately ahead
//(same row, next column)
public boolean isEnemyAhead()
//moves the plane up one row
public void up()
//moves the plane down one row
public void down()
//moves the plane forward one column
public void forward()
//drops one bomb on an enemy immediately below (same column)
public void dropBomb()
//returns true only if this plane has more bombs left to drop
public boolean hasMoreBombs()
}
The plane is initially in the top left space of a rectangular region
(of unknown size), as shown in the example below. The plane always
faces to the right. There is exactly one enemy in each column but the
first one. No enemies appear in the top row. The plane is carrying
exactly enough bombs to drop one on each enemy.
plane | | | | |
| | | | enemy |
| enemy | | | |
| | | enemy | |
| | | | |
| | enemy | | |
Write the method bombAllEnemies in the Plane
class. The plane should never go outside of the designated region,
and it should never move into the same space as an enemy. Whenever an
enemy is destroyed, that space becomes empty. As always, you are
encouraged to break the problem down into appropriate helper
methods.
public void bombAllEnemies()
Consider the CookieJar class below:
public class CookieJar
{
public CookieJar() { ... }
public boolean isEmpty() { ... }
public void addCookie(Cookie cookie) { ... }
public Cookie removeCookie() { ... }
}
Using only the methods listed above, implement the
countCookies method below, which should return the number of
cookies in the given CookieJar. You may remove cookies from
the jar, as long as you put them all back before you return.
public static int countCookies(CookieJar jar)