2

So I'm trying to implement a get method for my singly linked list class and I get the error: unreachable statement. I was wondering how can I fix this?

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;
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Dobrikella
  • 145
  • 1
  • 11
  • 4
    The lines after `return u.x` are unreachable because any code that is placed immediately after `return` will not be run. – Anil Oct 12 '19 at 02:18
  • 1
    Can you explain in your own words, what `return` does? – Tom Oct 12 '19 at 02:19
  • it returns a value to represent the function – Dobrikella Oct 12 '19 at 02:26
  • That's correct, so how should a method behave when you said "return that", but still expect it to keep doing other stuff, although it should return something? – Tom Oct 12 '19 at 02:29
  • 2
    Possible duplicate of [Why does Java have an "unreachable statement" compiler error?](https://stackoverflow.com/questions/3795585/why-does-java-have-an-unreachable-statement-compiler-error) – Alessandro Da Rugna Oct 12 '19 at 02:33

2 Answers2

1

The lines after return u.x are unreachable. Once a value is returned or an exception is thrown, the program exits the method.

Of course, you can still control what happens using an if statement:

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 the condition of the if statement isn't true, the program will skip it and return u.x instead.

See this tutorial for more about returning a value from a method.

Anil
  • 655
  • 1
  • 11
  • 25
0

Try this:

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; 
    }
}

Basically, all we're doing is moving the main logic of your method inside your validation logic. If i is out of bounds, throw an exception and return null, otherwise, execute your logic and return the result.

MarsAtomic
  • 10,436
  • 5
  • 35
  • 56