我想计算两个坐标之间的距离,这两个坐标存储在CVS文件中。 CVS文件中分别提到了X和Y坐标的两列。
我想在这些存储的点之间应用欧几里德距离公式并在控制台上打印结果。为此我已经将CVS文件的点作为数组检索,在控制台上打印该数组,并应用距离公式,之后我想按升序对它们进行排序,并选择具有最小距离的问题。
但我的问题是控制台上没有显示距离。代码如下:
import java.util.*;
import java.io.*;
public class distance {
public void euclidianDistanceFromFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
String line = br.readLine(); // for ignoring the header of file
int row = 0;
int col = 0;
double dist;
String[][] numbers = new String[8][2];
double Cordx[] = new double[8];
double Cordy[] = new double[2];
while ((line = br.readLine()) != null && row < 8) {
StringTokenizer st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
// get next token and store it in the array
numbers[row][col] = st.nextToken();
col++;
}
col = 0;
row++;
}
for (row = 0; row < 8; row++) {
for (col = 0; col < 2; col++) {
System.out.print(" " + numbers[row][col]);
}
System.out.println(" ");
}
for (row = 0; row < 8; row++) {
for (col = 0; col < 2; col++) {
Cordx[row] = Double.parseDouble(numbers[row][col]);
Cordy[col] = Double.parseDouble(numbers[row][col]);
}
}
for (int i = 0; i < Cordx.length; i++) {
dist = 0;
for (int j = 0; j < Cordy.length; j++) {
double diffx = Cordx[i + 1] - Cordx[i];
double diffy = Cordy[j + 1] - Cordy[j];
dist = dist + Math.sqrt(Math.pow(diffx, 2) + Math.pow(diffy, 2));
}
System.out.println("distance is" + "" + dist);
}
}
public static void main(String[] argv) throws IOException {
try {
distance dist = new distance();
dist.euclidianDistanceFromFile("src\\ploting\\ravm.csv");
// ravm is the cvs file from which i retrieve the points and calculate the distance.
} catch (Exception e) {
e.getMessage();
}
}
}
答案 0 :(得分:0)
首先,将e.getMessage()
更改为e.printStackTrace()
,您将能够看到ArrayIndexOutOfBoundsException
正在发生(您正在尝试访问某个数组中不存在的位置)
错误发生在这个循环中:
for (int i = 0; i < Cordx.length; i++) {
dist = 0;
for (int j = 0; j < Cordy.length; j++) {
double diffx = Cordx[i + 1] - Cordx[i];
double diffy = Cordy[j + 1] - Cordy[j];
请注意,当i
等于Cordx.length - 1
(又称“最后位置”)时,您尝试访问Cordx[i + 1]
(最后一个位置后的一个位置),从而导致错误。尝试以这种方式进行循环:
for (int i = 0; i < Cordx.length - 1; i++) {
dist = 0;
for (int j = 0; j < Cordy.length - 1; j++) {