-2

我在 Java 中遇到了这个函数的问题。我不明白为什么lastNodeAttributes==null真正的执行何时会跳转到return null;应有的位置,但是在那之后,它不是从函数返回,而是直接跳转到return fight...;最后。为什么第一个返回不退出但执行跳转到第二个条件部分返回?这怎么可能?请解释原因显然我不明白java的基础知识是如何工作的。

public Node undo() {
    Node lastNode=fight.getLastChild();
    NamedNodeMap lastNodeAttributes = lastNode.getAttributes();
    if(lastNodeAttributes == null) { return null; }
    else { 
        String lastNodeFighter = lastNodeAttributes.getNamedItem("fighter")
                                 .getNodeValue();
        String lastNodePoints = lastNodeAttributes.getNamedItem("points")
                                .getNodeValue();
        if(Integer.parseInt(lastNodeFighter) == 1) {
            fighter1score-=Integer.parseInt(lastNodePoints);    
        }
        else { fighter2score -= Integer.parseInt(lastNodePoints); }
        return fight.removeChild(fight.getLastChild());
    }
}
4

3 回答 3

0

首先开始调试您的应用程序。一个很好的调试教程可以在这里找到:http ://www.vogella.com/articles/EclipseDebugging/article.html

验证 lastNodeAttributes 是否真的为空。还要检查,如果该方法执行了两次,在第一种情况下 lastNodeAttributes 为空,而在第二种情况下则不是。

于 2012-08-24T09:54:01.927 回答
0

你描述的是不可能的。return 语句确实总是返回所声明的内容。为什么您可能会在调试器中看到此行为,有几种可能性

  • 您不是在调试您认为正在调试的代码。调试器可能正在加载与您想象的不同的类。尝试清理并重新编译您的代码并再次调试它。
  • 代码在发布模式下编译,并切换了您的语句。在发布模式下使用优化代码进行调试有时会导致调试器关闭,从而使错误语句显示为在调试器中执行的语句比实际执行的语句多。您确定您正在调试的代码未优化。
  • 如果您不仔细考虑,线程问题也会导致奇怪的跳转。如果您在 return 语句和多个线程运行中都有断点,那么一个线程可能会遇到第一个 return,然后另一个线程可能会遇到第二个 return。没错,这就是调试多线程应用程序的工作方式。

检查实际返回值也将确认确实只return执行了一条语句。通过在调用者而不是被调用者处放置断点来做到这一点

于 2012-08-24T09:57:16.057 回答
-1

Return does exit the method. check that you're using the latest compiled class. Try to do a clean build. Start debugging from the first line making sure that you're not running the same method twice. In case of doubt, add a system.out in the beginning of your class to make sure you're checking the right class version

于 2012-08-24T10:33:22.433 回答