HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Finding points with the shortest distance

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theshortestwithpointsdistancefinding

Problem

This takes in a user specified number of points then finds the two points with the shortest distance.

```
import java.util.Scanner;
import java.lang.Math;

public class FindNearestPoints
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);

System.out.print("Enter the number of points: ");
final int numOfPoints = scan.nextInt();

double[][] points = new double[numOfPoints][2];
double shortestDistance=0;
double distance=0;
String closestPoint1="";
String closestPoint2="";

//enter x,y coords into the ix2 table points[][]
for (int i=0; i<numOfPoints; i++)
{
System.out.print("Enter point x" + i + ": ");
points[i][0] = scan.nextDouble();
System.out.print("Enter point y" + i + ": ");
points[i][1] = scan.nextDouble();
}

//get the distance between the point in the ith row and the (m+1)th row
//and check if it's shorter than the distance between 0th and 1st
for (int i=0; i<numOfPoints; i++)
{
//use m=i rather than 0 to avoid duplicate computations
for (int m=i; m<numOfPoints-1;m++)
{
double dx = points[i][0] - points[m+1][0];
double dy = points[i][1] - points[m+1][1];
distance = Math.sqrt(dxdx + dydy);

//set shortestDistance and closestPoints to the first iteration
if (m == 0 && i == 0)
{
shortestDistance = distance;
closestPoint1 = "(" + points[0][0] + "," + points[0][1] + ")";
closestPoint2 = "(" + points[1][0] + "," + points[1][1] + ")";
}
//then check if any further iterations have shorter distances
else if (distance < shortestDistance)
{
shortestDistance = distance;

Solution

For starters, this code should use a Point class, consisting of an x and y location. Your variable points would then be Point[] rather than a two dimensional array. The Point class should have a method for reading values, printing values and calculating the distance between two points.

Then, using the Point class, your code would be dramatically simpler and easier to read. It might even be easier to write from scratch rather than try and fix what you have.

Context

StackExchange Code Review Q#9943, answer score: 10

Revisions (0)

No revisions yet.