gpt4 book ai didi

java - 错误抛出异常

转载 作者:行者123 更新时间:2023-12-01 13:06:47 24 4
gpt4 key购买 nike

我正在使用教科书中预先编写的类(class),并将它们实现到我的程序中。每次我尝试向树中添加新元素时,都会引发重复错误,我不知道为什么,而且我根本没有操作编写的代码。

基本上,程序会提示用户输入一些信息,并获取该信息并将其作为学生添加到二叉搜索树中,我从教科书中得到了以下内容:

AbstractBinaryTree 类:

public abstract class
AbstractBinarySearchTree<E extends Comparable<? super E>> implements
BinarySearchTree<E>

public void add( E element ) {
if ( element == null ) {
throw new SearchTreeException();
}
setRoot( add( null, this.root(), element ) );
size++;
}
...

LinkedBST 类:

public class LinkedBST<E extends Comparable<? super E>> extends
AbstractBinarySearchTree<E> {

public LinkedBST( E element ) {
if ( element == null ) {
throw new java.lang.IllegalArgumentException( "null element is illegal" );
}
this.root = new BSTNode<E> ( element );
this.size = 1;
}

protected void setRoot( BSTNode<E> newRoot ) {
this.root = newRoot;
}

protected BSTNode<E> add( BSTNode<E> parent, BSTNode<E> node, E element ) {
if ( node == null ) { // base case
node = new BSTNode<E> ( element );
node.parent = parent;
}
else { // recursive case
int compareResult = element.compareTo( node.element );
if ( compareResult < 0 ) { // recursive case - left
node.leftChild = add( node, node.leftChild, element );
}
else if ( compareResult > 0 ) { // recursive case - right
node.rightChild = add( node, node.rightChild, element );
}
else {
throw new SearchTreeException( "Duplicate element: " + element.toString() );
}
}

return node;
}
...

以及BinarySearchTree接口(interface),然后我实际上从一个单独的类调用该方法:

...
AbstractBinarySearchTree<Student> tree = new LinkedBST<Student>(); //this could be a problem?
...
tree.add(new Student(studentNumber, firstName, lastName, major, gpa));

所以,我知道这至少部分有效。我能够在树中添加至少一条记录,但是当我尝试添加第二条记录(无论信息如何)时,它会不断抛出 SearchTreeException a(也是预先编写的)并且不会添加任何其他人。我对抽象类和二叉搜索树仍然很陌生,所以我正在尽最大努力实现这一点,所以如果有人能看到我哪里出错了,那就太棒了!

最佳答案

如果您查看 Comparable 接口(interface)及其 compareTo(..)方法,它指出

Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

如果您看到 SearchTreeException,则表示这段代码

int compareResult = element.compareTo( node.element );
if ( compareResult < 0 ) { // recursive case - left
node.leftChild = add( node, node.leftChild, element );
}
else if ( compareResult > 0 ) { // recursive case - right
node.rightChild = add( node, node.rightChild, element );
}
else {
throw new SearchTreeException( "Duplicate element: " + element.toString() );
}

使用了 compareTo(..) 的实现,它返回了 0

从评论中,您声明您正在使用默认 (IDE-) 创建的方法实现,该实现始终返回 0。您需要修复此问题,以便您的 compareTo 方法按照 javadoc 中记录的方式工作。

关于java - 错误抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23205691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com