Java Puzzle 7: Cookies
Aug 07, 2012Learn how to count down with Count von Count and Cookie Monster!
If Count has two cookies and Cookie Monster eats one, how many cookies are left?
- One cookie.
Good. If Cookie Monster eats this one cookie, what does Count have left?
- An empty hand, no cookies. And a hungry Cookie Monster.
Great. Now, for the grand finale: if Cookie Monster then eats another cookie, what does Count have in his hand?
- Minus one cookie!
If cookies were Strings, could you write the Cookie Monster? The class Count
is given:
package count;
import monster.CookieMonster;
public class Count {
public static void main(String[] args) {
String noCookie = CookieMonster.eat("cookie");
if (noCookie.isEmpty() && CookieMonster.eat(noCookie).length() < noCookie.length()) {
// The goal is to reach this line
System.out.println("Minus one cookie!");
}
}
}
Edit the Cookie Monster to make it work:
package monster;
public class CookieMonster {
public static String eat(String cookie) {
return cookie.substring(0, cookie.length() - 6);
}
}
The usual puzzle rules apply (setAccessible()
is not allowed!). If you found the solution, post it as a comment here below. These comments stay private, and become public later on the next blog post.