日期:2014-05-20 浏览次数:20718 次
package com.common.test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) throws Exception {
List<Point> pointList = new ArrayList<Point>();
FileReader fr = new FileReader("d:\\data.txt");
BufferedReader reader = new BufferedReader(fr);
String str = null;
while(true){
str = reader.readLine();
if(str == null) {
break;
}
pointList.add(new Point(str.split(",")));
}
int length = pointList.size();
int count = 0;//int count = length * (length - 1) / 2; 这样就不用再循环里加了
double totalDistance = 0;
for(int i = 0; i < length; i++) {
Point p1 = pointList.get(i);
for(int j = i + 1; j < length; j++) {
Point p2 = pointList.get(j);
count++;
totalDistance += Math.sqrt(Math.pow(p2.getX() - p1.getX(), 2) + Math.pow(p2.getY() - p1.getY(), 2));
}
}
double avgDistance = totalDistance / count;
System.out.printf("平均距离为:%.2f", avgDistance);
}
}
class Point {
private int x;
private int y;
public Point() {
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(String x, String y) {
this.x = Integer.parseInt(x.trim());
this.y = Integer.parseInt(y.trim());
}
public Point(String[] arr) {
this.x = Integer.parseInt(arr[0].trim());
this.y = Integer.parseInt(arr[1].trim());
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}