-2

I am sure this repeats something, but yet due to short time I have to ask you straight forward help. How to convert Ternary (: and ?) operator into IF-ELSE statement in Java?

public Integer get(Integer index) {
    if (first == null) {
        return null;
    }
    MyNode curNode = first;
    while (index >= 0) {
        if (index == 0) {
            return curNode == null ? null : curNode.getValue();
        } else {
            curNode = curNode == null ? null : curNode.getNext();
            index--;
        }
    }
    return null;
}

What I did tried, but it gave me wrong output (this is all about LinkedList) is modifying it to:

    while (index >= 0) {
        if (index == 0) {
            // pre-modified -> return curNode == null ? null : curNode.getValue();
            if (first == null) {
                return null;
            } else {
                return curNode.getValue();
            }
        } else {
            if (curNode != null) {
                return curNode.getNext().getValue();
                //return null;
            } else {
                return null;
            }
            // pre-modified -> curNode = curNode == null ? null : curNode.getNext();
            // pre-modified -> index--;
        }
    }
apex_point
  • 21
  • 5

1 Answers1

0

In addition to that it was necessary also to fix part after else to:

else {
                if (curNode != null) {
                    curNode = curNode.getNext();
                    index--;
                    //return null;
                } else {
                    curNode = null;
                }
                // pre-modified -> curNode = curNode == null ? null : curNode.getNext();
                // pre-modified -> index--;
            }

Question solved.

apex_point
  • 21
  • 5