Java 从其他类调用方法
我尝试递归调用search,或者使用带有rootNode的search(它是BSTN)调用search,这会给我一个错误,表示类型错误;或者使用rootNode的子树调用getNode(错误,表示类型BST未定义),这会给我一个错误,表示类型错误Java 从其他类调用方法,java,binary-search-tree,Java,Binary Search Tree,我尝试递归调用search,或者使用带有rootNode的search(它是BSTN)调用search,这会给我一个错误,表示类型错误;或者使用rootNode的子树调用getNode(错误,表示类型BST未定义),这会给我一个错误,表示类型错误 package sizebst; public class sizeBST { sizeBSTN rootNode; public SizeBST(BSTN root){ rootNode = root; } public bo
package sizebst;
public class sizeBST {
sizeBSTN rootNode;
public SizeBST(BSTN root){
rootNode = root;
}
public boolean search(int target){
//isn't complete but I want to recrusively search the tree calling methods from the other class
getNode(rootNode.LSubtree, target);
}
这是我想从中调用getNode的方法
package sizebst;
public class SizeBSTN {
SizeBSTN LSubtree;
SizeBSTN RSubtree;
int data;
int size;
public SizeBSTN(int data){
LSubtree = null;
RSubtree = null;
this.data = data;
size = 1;
}
public static SizeBSTN getNode(SizeBSTN node, int target){
// isn't working yet but it finds a node and returns it.
}
}
因为
getNode
是static
方法,来自SizeBSTN
类
SizeBSTN.getNode(rootNode.LSubtree, target);
反而
getNode(rootNode.LSubtree, target);
另一种方法是使用静态导入此方法
import static sizebst.SizeBSTN.getNode;
现在您可以不使用类引用来调用它。我已经尝试过了,但现在它可以在以前没有的情况下使用。你能解释一下为什么>@PaulthePirate它可以工作,因为如果你从它的类之外调用静态方法,那么所有的静态方法都是通过它的类来调用的。我不知道为什么早些时候它对你不起作用。也许你没有编译SizeBSTN源代码?也许你拼错了什么。很难说。@paulate您确实需要开始使用一些IDE,比如Eclipse或Netbeans,并让代码自动缩进。看看这里。您将看到最后一个
else
未与任何if
连接。还有
就在if
之后,这可能不是您想要的。它是分号。对不起,我是诵读困难症患者,总是忽略这些事情。我使用eclipse,它会自动缩进,但我不知道如何在这里维护它。在eclipse中按ctrl+shift
+F
可以正确格式化代码,然后复制粘贴到文章中,如果代码需要其他格式,那么在代码上使用{}
。