2

所以我试图为我的单链表类实现一个 get 方法,但我得到了错误:unreachable statement。我想知道如何解决这个问题?

public T get(int i) {
    // TODO: Implement this
    Node u = head;
    for(int j = 0; j < i; j++){
        u = u.next;
    }
    return u.x; 
    if (i < 0 || i > n - 1) throw new IndexOutOfBoundsException();
    return null;
}
4

2 回答 2

1

后面的行return u.x无法访问。一旦返回值或抛出异常,程序就会退出该方法。

当然,您仍然可以使用if语句控制发生的情况:

public T get(int i) {
    if (i < 0 || i > n - 1)
        throw new IndexOutOfBoundsException();
    // TODO: Implement this
    Node u = head;
    for (int j = 0; j < i; j++)
        u = u.next;
    return u.x;
}

如果if语句的条件不成立,程序将跳过它并返回u.x

有关从方法返回值的更多信息,请参阅本教程

于 2019-10-12T02:35:39.960 回答
0

尝试这个:

public T get(int i){
    if (i < 0 || i > n - 1) {
        throw new IndexOutOfBoundsException();
    } else {
        Node u = head;
        for(int j = 0; j < i; j++){
            u = u.next;
        }
        return u.x; 
    }
}

基本上,我们所做的只是将您的方法的主要逻辑移动到您的验证逻辑中。如果i超出范围,则抛出异常并返回 null,否则,执行您的逻辑并返回结果。

于 2019-10-12T02:34:58.810 回答