Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think you have several issues. It looks like you have a class like this:</p> <pre><code>public class Point { public double x; public double y; } </code></pre> <p>You should probably add a method to your class that looks like this:</p> <pre><code>public double distance(Point p) { return Math.hypot(this.x - p.x, this.y - p.y); } </code></pre> <p>And another one:</p> <pre><code>public Point getClosestPoint(List&lt;Point&gt; pts) { double minDistSoFar = Double.MAX_VALUE; Point rval = null; for (Point p : pts) { if (p.x == this.x &amp;&amp; p.y == this.y) { continue; } double pDist = this.distance(p); if (pDist &lt; minDistSoFar) { minDistSoFar = pDist; rval = p; } } } </code></pre> <p>Now your algorithm can become this:</p> <pre><code>public void connectingPoints() { ArrayList&lt;Point&gt; externals = new ArrayList&lt;Point&gt;(); for(Point p : externals) { Point minPoint = p.getClosestPoint(externals); getGraphics().drawLine(point.x, point.y, minPoint.x, minPoint.y); repaint(); } } </code></pre> <p>EDIT: Your original problem is probably that you index "i" in your loop examining the value of j. Also, here is a rewrite with a simple (and workable) rewrite of your code.</p> <pre><code>public void connectingPoints() { ArrayList&lt;Point&gt; externals = new ArrayList&lt;Point&gt;(); for(int i = 0; i&lt;externals.size(); i++) { Point point = externals.get(i); Point minPoint = externals.get((i+1) % externals.size()); int minXDistance = minPoint.x-point.x; int minYDistance = minPoint.y-point.y; double minDist = Math.hypot(minXDistance, minYDistance); for(int j = 0; j &lt; externals.size(); j++) // &lt;- you had i++ here! { if (i == j) { continue; } Point testPt = externals.get(j); double dist = Math.hypot(point.x - testPt.x, point.y - testPt.y); if (dist &lt; minDist) { minDist = dist; minPoint = testPt; } } getGraphics().drawLine(point.x, point.y, minPoint.x, minPoint.y); repaint(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload