初学Java 二维数组找出最近的两个点
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 double[][] points = new double[numberOfpoints][2]; 10 System.out.print("Enter " + numberOfpoints + " points: "); 11 for (int i = 0; i < points.length; i++) { 12 points[i][0] = input.nextDouble(); 13 points[i][1] = input.nextDouble(); 14 } 15 16 int p1 = 0, p2 = 1; 17 double shortesDistance = distance(points[p1][0], points[p1][1], points[p2][0], points[p2][1]); 18 for(int i = 0; i < points.length; i++) { 19 for(int j=i+1; j<points.length; j++) { 20 double distance = distance(points[i][0], points[i][1], points[j][0], points[j][1]); 21 22 if (shortesDistance > distance) { 23 p1 = i; 24 p2 = j; 25 shortesDistance = distance; 26 } 27 } 28 } 29 System.out.println("The closest tow points are " + "("+points[p1][0]+", "+points[p1][1]+")and("+points[p2][0]+", "+points[p2][1]+")"); 30 31 } 32 public static double distance( 33 double x1, double y1, double x2, double y2) { 34 return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); 35 } 36 }