【问题标题】:java - unreachable statement help (linked lists)java - 无法访问的语句帮助(链表)
【发布时间】:2020-02-09 12:21:47
【问题描述】:

所以我试图为我的单链表类实现一个 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;
}

【问题讨论】:

  • return u.x 之后的行无法访问,因为任何紧跟在return 之后的代码都不会运行。
  • 你能用你自己的话解释一下return是做什么的吗?
  • 它返回一个值来表示函数
  • 那是正确的,那么当你说“返回那个”时,一个方法应该如何表现,但仍然期望它继续做其他事情,尽管它应该返回一些东西?

标签: java unreachable-statement


【解决方案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

有关从方法返回值的更多信息,请参阅this tutorial

【讨论】:

    【解决方案2】:

    试试这个:

    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,否则,执行您的逻辑并返回结果。

    【讨论】:

    • 好收获。懒惰的复制/粘贴。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    相关资源
    最近更新 更多