0

I'm learning about linked-list in Java and trying to make an function to add new point into Linked- List with given index. please help me review my code then tell me what I'm doing wrong here. Thank you so much in advance!!!.

My program has 2 class name Waypoint and TourElement. I also have some test cases.

Waypoint

public class Waypoint {
    int x;
    int y;

    public int getX() {
        return this.x;
    }

    public int getY() {
        return this.y;
    }

    public void setXY(int x, int y) {
        this.x = x;
        this.y = y;
    }

    int[] toArray() {
        int array[] = new int[2];
        array[0] = getX();
        array[1] = getY();
        return array;
    }

    @Override
    public String toString() {
        String convertToString = "(" + getX() + "/" + getY() + ")";
        return convertToString;
    }

TourElement

public class TourElement {
    private Waypoint points;
    private TourElement next;

    public void setWaypoint( Waypoint points) {
        this.points = points; 
    }

    public void setNext(TourElement next) {
        this.next = next;
    }

    Waypoint getWaypoint() {
        return this.points;
    }

    TourElement getNext() {
        return this.next;
    }

    boolean hasNext() {
        if(this.next != null) {
            return true;
        }
        return false;
    }

    int getNoOfWaypoints() {//  return the number of waypoints in the list
    int count = 1;
    TourElement current = this;
    while(current.next != null) {
        count++;
        current = current.next;
        System.out.println(count);
    }
    return count;
}

Here is function to insert new point with given index:

TourElement insertAt(int index, Waypoint waypoint) {
    int lengthLinkList = getNoOfWaypoints();
    TourElement current = this;
    int count = 0;
    if(waypoint == null || index < 0 || index > lengthLinkList) {
        return this;
    } else {
        if(index == 0) {
            TourElement newElement = new TourElement();
            newElement.setWaypoint(waypoint);
            newElement.setNext(this);
            return newElement;
        } else {
            while(current.next != null) { //I think I'm doing wrong here when trying to add new points.
                if(index == count) {
                    TourElement newElement = new TourElement();
                    current.setNext(current);
                    newElement.setWaypoint(waypoint);
                    newElement.setNext(current.next);
                    return newElement;
                }
                count++;
                current = current.next;
           }
           if(current.next == null) {
            TourElement newElement = new TourElement();
            current.setNext(newElement);
            newElement.setWaypoint(waypoint);
            newElement.setNext(null);
           }
        }
        return this;
    }
}

Here is my test case: //Create Element List:

private Waypoint createWaypoint(int x, int y) {
        Waypoint wp = new Waypoint();
        wp.setXY(x, y);
        return wp;
    }

    /**
     * Creates a ElementList with the given waypoints.
     * @param waypoints array of waypoints to use, the coordinates of the waypoints are also in an array
     * @return List of elements with the given waypoints
     * @pre at least one waypoint has to be in array
     */
    private TourElement createElementList(int[][] waypoints){
        assert waypoints.length > 0;
        TourElement elem = new TourElement();
        int lastIndex = waypoints.length-1;
        Waypoint wp = createWaypoint(waypoints[lastIndex][0], waypoints[lastIndex][1]);
        elem.setWaypoint(wp);
        for (int i = lastIndex-1; i >= 0 ; i--) {
            wp = createWaypoint(waypoints[i][0], waypoints[i][1]);
            elem = elem.addStart(wp);
        }
        return elem;
    }

Test case 1: Passed

@Test
public void testInsertAt_BeforeFirst() {
    TourElement elem = createElementList(new int[][] {{1, 1}, {3, 3}});
    Waypoint wp = createWaypoint(0, 0);
    elem = elem.insertAt(0, wp);
    assertArrayEquals(new int[] {0, 0}, elem.getWaypoint().toArray());
    assertArrayEquals(new int[] {1, 1}, elem.getNext().getWaypoint().toArray());
    assertArrayEquals(new int[] {3, 3}, elem.getNext().getNext().getWaypoint().toArray());
    assertNull(elem.getNext().getNext().getNext());
}

Test cases 2: Failed

The error is: array first differed at element[0]; expect <2> but was:<3>

  @Test
    public void testInsertAt_Second() {
        TourElement elem = createElementList(new int[][] {{1, 1}, {3, 3}});
        Waypoint wp = createWaypoint(2, 2);
        elem = elem.insertAt(1, wp);
        assertArrayEquals(new int[] {1, 1}, elem.getWaypoint().toArray());
        assertArrayEquals(new int[] {2, 2}, elem.getNext().getWaypoint().toArray());
        assertArrayEquals(new int[] {3, 3}, elem.getNext().getNext().getWaypoint().toArray());
        assertNull(elem.getNext().getNext().getNext());
    }

Test case 3: passed

@Test
public void testInsertAt_Last() {
    TourElement elem = createElementList(new int[][] {{1, 1}, {3, 3}});
    Waypoint wp = createWaypoint(4, 4);
    elem = elem.insertAt(2, wp);
    assertArrayEquals(new int[] {1, 1}, elem.getWaypoint().toArray());
    assertArrayEquals(new int[] {3, 3}, elem.getNext().getWaypoint().toArray());
    assertArrayEquals(new int[] {4, 4}, elem.getNext().getNext().getWaypoint().toArray());
    assertNull(elem.getNext().getNext().getNext());
}

In the function insertAt(index, waypoint), this function passed when index = 0 or index = last. But I don't understand why second test case doesn't pass. Please help me!!

3
  • At which point is test case 2 failing and with what message? Commented Jun 2, 2019 at 10:59
  • you need to show us createElementList() because you are using its return value to do the insert Commented Jun 2, 2019 at 11:20
  • I'm sorry, I edited the code and show createElementList() above the test case Commented Jun 2, 2019 at 11:41

1 Answer 1

1

The problem is detectable if you run with debugger. So, first, I don't know which IDE (if at all) you are using, but I highle recommend you familiarize yourself with this tool.

Now, debugging your code, I found that the problem occurs when you want to add an element before the last one in the list (as is the case with the failed test case). your loop while(current.next != null) stops at the last element. you assume that at this point you want to insert at the end of the list, while in fact, you want to insert before the last element. since this is a learning exercise, I will let you solve this one by yourself.

one more comment: when adding element in the middle of the list, you needlessly keep iterating the loop after you've already did the insert.

good luck!

Sign up to request clarification or add additional context in comments.

7 Comments

I really dont understand that. I use netbean 8.2 for my assignment. and about your idea, I know that while(current.next != null) stops at the last element, and I have an condition if(index == count) to insert before last element. What i'm doing wrong in this code?
so use the IDE built in debugger to run through your code
I know the error, but I don't know how to fix my code. It look like when I run the function, it can not insert new element at the given index. If you know the problem, pls tell me what i'm doing wrong..
I tried to explain the problem in my answer - the problem is when you try to insert an element to the index before the last element in the list
also, look inside the if(index == count). you are calling newElement.setNext() twice, that can't be right
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.