[英]binary search tree, insert method won't compile
我试图用Java编写自己的二进制搜索树。 我已经编写了所有方法,现在尝试编写一个程序来测试这些方法。
但是,当我尝试实现“插入”方法时,它将无法编译,并且我也不知道为什么。
public class lab05driver {
public static void main(String[] args) {
BST q = new BST();
int a = 5;
String b = "jed";
double c = 1.8;
char d = 'r';
boolean e = false;
int f = 35;
String g = "yay";
double h = 2.1;
char i = 'i';
boolean j = true;
Integer k = 5;
q.insert(k);
}}
我的BST类如下所示:
public class BST implements myBST {
private myTreeNode root;
public BST() {
}
public void insert(Comparable x) {
if(root == null) {
root = new myTreeNode();
root.data = x;
} else if ( !lookup(x) ) {
root.insert(x);
}
}
...more code...
}
而且,myBST看起来像:
public interface myBST {
public void insert(Comparable x);
public void delete(Comparable x);
public boolean lookup(Comparable x);
public void printPreOrder();
public void printInOrder();
public void printPostOrder();
}
最后,myTreeNode看起来像:
public class myTreeNode {
public myTreeNode() {
}
public Comparable data ;
public myTreeNode leftchild;
public myTreeNode rightchild;
public myTreeNode parent;
public void insert(Comparable d) {
//if less than
//does left exist? if it doesnt, make it, give it d
//if it exists call insertrecursive on rightchild
if(d.compareTo(data) <= 0) {
if(leftchild != null) {
leftchild.insert(d);
} else {
leftchild = new myTreeNode();
leftchild.data = d;
leftchild.parent = this;
}
} else {
if(rightchild != null) {
rightchild.insert(d);
} else {
rightchild = new myTreeNode();
rightchild.data = d;
rightchild.parent = this;
}
}
}
...more code...
}
它在lab05driver中的“ q.insert(k)”处引发错误。 任何帮助/建议将不胜感激...
~~~~~编辑:抱歉,我jsut复制了该错误...有一个主要方法,Integer k是一个整数...获取命令行的错误是:警告:[unchecked]未选中对compareTo(T的调用)作为原始类型java.lang.Comparable的成员
q.insert(k);
是一个声明。 语句必须在方法中,但当前不在方法中。
因此,请执行以下操作:
public class lab05driver
{
public static void main( String[] args )
{
BST q = new BST();
int a = 5;
String b = "jed";
double c = 1.8;
char d = 'r';
boolean e = false;
int f = 35;
String g = "yay";
double h = 2.1;
char i = 'i';
boolean j = true;
Integer k = 1; // changed because "Integer k = "test";" doesn't compile
q.insert(k);
}
}
请注意我用于该方法的签名。 这是Java视为输入方法(程序将在其中启动)的签名。
我可以看到的最明显的问题是:
Integer k = "test";
k必须是某种整数-您已为其分配了一个String。 这不是有效的分配。 有效值为-1、0、1等-任何整数值。
一旦指定了值(或将k更改为String
类),代码就可以了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.