Question: Recursive java problem. i get the jist of this problem but im really struggling with it, or with recurssion more i guess. please help me
Recursive java problem. i get the jist of this problem but im really struggling with it, or with recurssion more i guess. please help me slove it.
On your birthday, you receive a box in the mail. You open it up, expecting to find a present, but inside there are just more boxes. You open one of them, and it has an actual present for you in it, but the next one contains a present along with several more boxes! And inside each of those boxes, sometimes you find a present, sometimes you find more boxes, or even some of each!
Write a recursive method that prints out the descriptions of all the presents (but not including the boxes). You can start with the class Thing, where a Thing has a method isPresent that tells you whether it's a present or a box, and if it is a box, you can call the method getContents to get a list of all the Things it contains.
You can find code for the Thing class here.
Your method should look like this:
public static void listAllPresents(Thing thing) { // TODO } Here is the Thing Class:
package lab9; import java.util.ArrayList; /** * A Thing represents something that could either be a birthday present, * or it could be a box containing more Thing objects. */ public class Thing { /** * Contents of this thing, if it's a box. */ private ArrayList contents; /** * True if this thing is a present, false if it's a box. */ private boolean isPresent; /** * String description of this thing, if it's a present. */ private String description; /** * Constructs a thing that is a present with the given description. * @param givenDescription */ public Thing(String givenDescription) { description = givenDescription; isPresent = true; contents = null; } /** * Constructs a thing that is an empty box. */ public Thing() { description = "box!"; isPresent = false; contents = new ArrayList(); } /** * Adds a thing to this thing's contents. This thing must * be a box for this to work. * @param t */ public void addThing(Thing t) { contents.add(t); } /** * Returns true if this thing is a present, false if it's a box. * @return */ public boolean isPresent() { return isPresent; } /** * Returns a list of the contents of this thing, or null if * it's not a box. * @return */ public ArrayList getContents() { return contents; } /** * Returns the description of this thing. * @return */ public String getDescription() { return description; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
