Home » Java » java – Unreachable statement after conditional-Exceptionshub

java – Unreachable statement after conditional-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

The following code gives the error: Unreachable statement for current= current.getmNextNode();
How can it be solved?

public int indexOf(E element) {

    Node current = head;
    for (int i = 0; i < size; i++) {
        if (current.getmElement().equals(element)) ;
        {
            return i;
        }
        current = current.getmNextNode();
    }

    return -1;
}
How to&Answers:

You have an extra semicolon between the if statement, and what is supposed to be its body. The way you wrote it, the return i; statement will be executed regardless of the result of the condition.

public int indexOf(E element) {
  Node current = head;

  for (int i = 0; i < size; i++) {
    if (current.getmElement().equals(element)) {
      return i;
    }

    current= current.getmNextNode();
  }
  return -1;
}