Write a recursive method body for the hasLabel method whose contract is given be
ID: 3802472 • Letter: W
Question
Write a recursive method body for the hasLabel method whose contract is given below. Do not use magic numbers, breaks or multiple returns. The XML Tree Interface API is attached./** * Reports whether the given label appears as a tag or text * in the given XML Tree. * @param xml * the XML Tree * @param label * the label name * @return true if the given label appears in the given XML Tree, * false otherwise * @ensures * hasLabel = * [true if the given label appears in the given XML Tree, * false otherwise] * */private static boolean hasLabel (XML Tree xml, String label)Explanation / Answer
To make the check declare a boolean variable flag and make it static global variable method.
This makes the variable flag to have the current value,every time the function is being called instead of the default changing of value.
public static final boolean flag=false;
private static boolean hasLabel(XMLTree xml, String label) {
if (xml.isTag() && !flag) {
for (int i = 0; i < xml.numberOfChildren(); i++) {
hasLabel(xml.child(i), label);//recursion implemented
System.out.println("label is " + xml.label());
if (xml.label().equals(label)) {
flag = true;
System.out.println(flag);
return flag;
}
}
}
return flag;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.