单向链表程序的 if 语句错误



我正在开发SinglyLinkedList编写所有方法的程序。有一个方法deleteAtGiven(int t),如果变量 t 小于 0 或 t 大于或等于大小,它会IndexOutOfBoundsException抛出异常,但它给了我一个 无法访问 语句的错误。

我试图将其写在 else-if 语句中并反转 else=if 语句,但它不起作用。

这是我的代码

public E deleteAtGiven(int t){
if(isEmpty()) return null;
throw new IndexOutOfBoundsException("List is Empty");
else if (t<0 ||t>=size()){ 
throw new IndexOutOfBoundsException("Invalid Position");
}
}

它应该引发异常。

如果我们更改代码的换行符和缩进以符合 Java 标准,我怀疑您会看到问题所在:

public E deleteAtGiven(int t){
if(isEmpty()) 
return null;
throw new IndexOutOfBoundsException("List is Empty");
else if (t<0 ||t>=size()){ 
throw new IndexOutOfBoundsException("Invalid Position");
}
}

throw 指令不受 if 语句控制。 相反,每次调用该方法时都会发生抛出,无论是否触发 if 语句。 这会导致抛出后的所有代码都无法访问。

public E deleteAtGiven(int t){
if(isEmpty()) return null;
throw new IndexOutOfBoundsException("List is Empty");
else if (t<0 ||t>=size()) 
throw new IndexOutOfBoundsException("Invalid Position");
}

在上面的代码中,isEmpty(),检查链表是否为空。如果是这样,则返回一个null值。
如果 linkedlist 不为空,则执行 if 条件正下方的语句。
在这里它抛出IndexOutOfBoundsException.
因此,else if 部分中的代码将永远不会执行,这会导致 throw 语句下方的语句无法访问。

根据我对您要做的事情的理解,您必须执行以下操作:

public E deleteAtGiven(int t){
if(isEmpty()) {
throw new IndexOutOfBoundsException("List is Empty");
}
else if (t<0 ||t>=size()){
throw new IndexOutOfBoundsException("Invalid Position");
}else{
// rest logic resides here.
}
}

解释:
如果链表已经为空,则只需抛出空异常。否则,如果元素的索引无效,则抛出异常"无效位置"。

首先,如果 if 没有达到,你就不能做其他事情。 如果您返回,则异常将不会到达。 如果您抛出异常,该功能将自动制动,因此您可以这样做

public E deleteAtGiven(int t) {
if (isEmpty())
throw new IndexOutOfBoundsException("List is Empty");
else if (t < 0 || t >= size()) 
throw new IndexOutOfBoundsException("Invalid Position");
else return null;
}

当它通过所有情况时,如果不通过情况,您将返回 null 或任何您想要的内容,它将运行异常

返回后不能使用 throw,它将无法到达,

public E deleteAtGiven(int t){
if(isEmpty())
throw new IndexOutOfBoundsException("List is Empty");
else if (t<0 ||t>=size()) 
throw new IndexOutOfBoundsException("Invalid Position");
}

最新更新