开发者

Java: why isn't the updated value being returned?

开发者 https://www.devze.com 2023-02-18 02:34 出处:网络
public static int getElementIdx (DOMElement elt) { int count = 1; for (DOMElement sib = (DOMElement) elt.getPreviousSibling();
  public static int getElementIdx (DOMElement elt) {
        int count = 1;

        for (DOMElement sib = (DOMElement) elt.getPreviousSibling(); 
                 sib != null; 
                 sib = (DOMElement) sib.getPreviousSibling())
        {
            System.out.println("sib " 
              + sib.getTagName () + " elt " + elt.getTagName ());
            if (sib.ELEMENT_NODE == sib.getNodeType () &&
              sib.getTagName () == elt.getTagName ()) {
                    System.out.println (cou开发者_如何学Pythonnt);
                    count++;
                }
        }
        return count;
    }

count always returns 1. However, inside the for loop, it returns the incremented count value. This is really strange, I thought declaring a local variable count outside of the for loop should work....


The count usage is fine--the inner if statement is likely never true.

The culprit is likely to be

sib.getTagName() == elt.getTagName()

You need to check String equality using equals():

sib.getTagName().equals(elt.getTagName())
0

精彩评论

暂无评论...
验证码 换一张
取 消