[英]Java: cannot be resolved to a type
我下面定義嵌套類的代碼有什么問題? 它抱怨說: CNode無法解析為一種類型
package compute;
public class CBTree {
public CNode root;
public void addNode(int key){
CNode newNode = new CNode(key);
// now to find an appropriate place for this new node
// 1 it could be placed at root
if (null == root){ // to void c-style mistakes a==null ( with a=null) is not prefered
root = newNode;
}
// if not then find the best spot ( which will be once of the
CNode currentRoot = root;
while(true){
if (key < currentRoot.key){
if (null == currentRoot.left){
currentRoot.left = newNode;
break;
} else{
currentRoot = currentRoot.left;
} else{//if (key < currentRoot.key)
if (null == currentRoot.right){
currentRoot.right = newNode;
break;
}else{
currentRoot = currentRoot.right;
}
}
}//while
class CNode{
int key;
public CNode left;
public CNode right;
/**
* Constructor
*/
public CNode(int key){
this.key = key;
}
/**
* Display the node
*/
public void display(){
System.out.println("node:"+ key);
}
}
}
CNode
類在addNode
方法中定義。
將您的CNode
類放在addNode
方法之外,以便可以解決它。
另外,您將需要調整if / else邏輯,因為您當前在同一個if
上有兩個else
塊,它們不會編譯。
除了rgettman的建議外,您還可以將CNode設為CBTree中的靜態類,並使用CBTree.CNode對其進行實例化。
此外,您的包圍看起來也很不錯。 您的while塊結尾的注釋似乎與if塊相對應。
這個問題與此非常相似。
將嵌套類放入方法中意味着在該方法運行之前或之后引用該類的任何能力都會失敗。 將嵌套類放在主類中,但不能放在任何方法之外。
以下代碼需要放置在addNode
方法之外
class CNode{
int key;
public CNode left;
public CNode right;
/**
* Constructor
*/
public CNode(int key){
this.key = key;
}
/**
* Display the node
*/
public void display(){
System.out.println("node:"+ key);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.