-2

I created a few points and added them to a LinkedList. I am trying to loop through each point, drawing a line between it and all the other points. I created these 2 for loops to do just that, however, only the second one loops through the LinkedList. There are 4 points in the list during my testing.

Here is my code:

    public void draw(Graphics2D g){
    g.setColor(Color.BLACK);
    g.setStroke(new BasicStroke(10));

    System.out.println("Linked List Size: " + points.size());

    for(int i = 0; i < points.size(); i++){
        System.out.println("Current Point: " + points.get(i));
        Point2D tempPoint = points.get(i);

        for(i = 0; i < points.size(); i++){
            Point2D tempEndPoint = points.get(i);
            g.drawLine((int)tempPoint.getX(), (int)tempPoint.getY(), (int)tempEndPoint.getX(), (int)tempEndPoint.getY());
            System.out.println("" + (int)tempPoint.getX() + " " + (int)tempPoint.getY() + " " + (int)tempEndPoint.getX() + " " +(int)tempEndPoint.getY());
        }
    }
}

The print statement's are just for testing purposes. Thanks.

4 Answers4

1

You are using the same variable index i, change to another letter like j.

for(int i = 0; i < points.size(); i++){
    System.out.println("Current Point: " + points.get(i));
    Point2D tempPoint = points.get(i);

    for(int j = 0; j < points.size(); j++){
        Point2D tempEndPoint = points.get(j);
        g.drawLine((int)tempPoint.getX(), (int)tempPoint.getY(), (int)tempEndPoint.getX(), (int)tempEndPoint.getY());
        System.out.println("" + (int)tempPoint.getX() + " " + (int)tempPoint.getY() + " " + (int)tempEndPoint.getX() + " " +(int)tempEndPoint.getY());
    }
}
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
  • Thanks, this fixed the problem... However now instead of drawing lines, only the points are drawn (tempPoint and tempEndPoint are equal). Any suggestions on how I might fix this this? Thanks again. –  Oct 24 '15 at 23:42
  • Fixed it... for tempEndPoint I was getting index i instead of j. –  Oct 24 '15 at 23:54
1

Both your loops use the variable 'i'.

Just use another name for the variable in your second loop.

Iltis
  • 81
  • 7
0

You are using the same counter i for both loops.

Michael Jaros
  • 4,586
  • 1
  • 22
  • 39
0

In the second loop you also use i therefore after the second loop i == points.size() and your first loop condition is false. Use j for the second loop for instance.