Lecture Videos
  1  import java.util.Scanner;
  2  
  3  public class FindNearestPoints {
  4    public static void main(String[] args) {
  5      Scanner input = new Scanner(System.in);
  6      System.out.print("Enter the number of points: ");
  7      int numberOfPoints = input.nextInt();
  8  
  9      // Create an array to store points
 10      double[][] points = new double[numberOfPoints][2];
 11      System.out.print("Enter " + numberOfPoints + " points: ");
 12      for (int i = 0; i < points.length; i++) {
 13        points[i][0] = input.nextDouble();
 14        points[i][1] = input.nextDouble();
 15      }
 16  
 17      // p1 and p2 are the indices in the points array
 18      int p1 = 0, p2 = 1; // Initial two points
 19      double shortestDistance = distance(points[p1][0], points[p1][1], 
 20        points[p2][0], points[p2][1]); // Initialize shortestDistance
 21      
 22      // Compute distance for every two points
 23      for (int i = 0; i < points.length; i++) {
 24        for (int j = i + 1; j < points.length; j++) {
 25          double distance = distance(points[i][0], points[i][1],
 26            points[j][0], points[j][1]); // Find distance
 27  
 28          if (shortestDistance > distance) {
 29            p1 = i; // Update p1
 30            p2 = j; // Update p2
 31            shortestDistance = distance; // Update shortestDistance 
 32          }
 33        }
 34      }
 35  
 36      // Display result
 37      System.out.println("The closest two points are " +
 38        "(" + points[p1][0] + ", " + points[p1][1] + ") and (" +
 39        points[p2][0] + ", " + points[p2][1] + ")");
 40    }
 41  
 42    /** Compute the distance between two points (x1, y1) and (x2, y2)*/
 43    public static double distance(
 44        double x1, double y1, double x2, double y2) {
 45      return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
 46    }
 47  }