Java 如何签入XMLTree并返回

Java 如何签入XMLTree并返回,java,xml,recursion,Java,Xml,Recursion,我很难理解为什么给出的值不正确 public static void main(String[] args) { SimpleReader in = new SimpleReader1L(); SimpleWriter out = new SimpleWriter1L(); boolean x = true; out.print("Enter a URL or file name for an XML source: "); String url = in

我很难理解为什么给出的值不正确

public static void main(String[] args) {
    SimpleReader in = new SimpleReader1L();
    SimpleWriter out = new SimpleWriter1L();
    boolean x = true;
    out.print("Enter a URL or file name for an XML source: ");
    String url = in.nextLine();
    XMLTree xml = new XMLTree2(url);
    out.print("Enter the name of a tag: ");
    String tag = in.nextLine();
    out.println(findTag(xml, tag));
}

/**
 * Reports whether the given tag appears in the given {@code XMLTree}.
 * 
 * @param xml
 *            the {@code XMLTree}
 * @param tag
 *            the tag name
 * @return true if the given tag appears in the given {@code XMLTree}, false
 *         otherwise
 * @ensures <pre>
 * findTag =
 *    [true if the given tag appears in the given {@code XMLTree}, false otherwise]
 * </pre>
 */
private static boolean findTag(XMLTree xml, String tag) {
    boolean result = false;
    if (xml.isTag()) {
        for (int i = 0; i < xml.numberOfChildren(); i++) {

            findTag(xml.child(i), tag);
            System.out.println("label is " + xml.label());
            if (xml.label().equals(tag)) {
                result = true;
                System.out.println(result);
            }
        }
    }

    return result;
}
}


当给定xml树时,代码将运行,以便找到树中存在的所有标记。它将每个标记与正在搜索的标记进行比较。如何使它在XML中找到给定的标记时,更新布尔变量并阻止它搜索更多内容。

有两种方法可以实现您想要的功能

一,。将布尔变量作为方法的静态全局变量

二,。将布尔变量作为参数传递给方法。 在处理该方法之前,只需检查变量的状态

像这样的

private static boolean findTag(XMLTree xml, String tag,boolean result) {       
    if (xml.isTag() && !result) {
        for (int i = 0; i < xml.numberOfChildren(); i++) {

            findTag(xml.child(i), tag,result);
            System.out.println("label is " + xml.label());
            if (xml.label().equals(tag)) {
                result = true;
                System.out.println(result);
                return result;
            }
        }
    }

    return result;
}