我没有从CVS文件输出实际距离



我想计算存储在 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();
        }
    }
}

首先,将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++) {

最新更新