2017-03-21 5 views
0

CVSファイルに格納されている2つの座標の距離を計算します。 CVSファイルには、それぞれX座標とY座標の2つの列があります。CVSファイルの出力として実際の距離が得られません

これらの保存された点の間にEuclidean Distance Formulaを適用し、その結果をコンソールに出力したいと考えています。同じものについては、CVSファイルのポイントを配列として取得し、その配列をコンソールに出力し、Distance Formulaを適用した後、昇順にソートし、さらに問題が発生する距離を最小にするものを選択します。

しかし私の問題は、距離がコンソールに表示されていないことです。 (あなたには、いくつかの配列のinexistent位置にアクセスしようとしている)まず、e.printStackTrace()に変更e.getMessage()

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

'ダブルdiffy = Cordy [J + 1] -Cordy [j]は、' => j = 1のとき( 'Cordx'についても同じこと)あなたは、あなたのアレイの外側読みます – Fefux

答えて

0

を、あなたはArrayIndexOutOfBoundsExceptionが起こっていることを確認することができます:コードは以下に言及されています。

エラーはこのループである:iがあることはCordx.length - 1(別名「最後の位置」)に等しいこと

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]; 

注、あなたが原因、アクセスCordx[i + 1](最後のものの後に一つの位置)にしてみてくださいエラー。ループをこの方法で行うようにしてください:

for (int i = 0; i < Cordx.length - 1; i++) { 
     dist = 0; 
     for (int j = 0; j < Cordy.length - 1; j++) { 
関連する問題