2017-03-03 77 views
1

我有被組織這樣的1000個數據點的數據文件:讀取數據點

1000 
16 11 
221 25 
234 112 
348 102 
451 456 

我試圖讀取該文件到我的程序並找到點的安排這導致了最短的總點到點距離。由於我對列表很少有經驗,即使閱讀數據點,我也遇到了很多麻煩。有沒有更好的方法來解決這個問題?你如何通過最近鄰居算法運行列表?

public static void main(String[] args) throws IOException { 
    File file = new File("output.txt"); 
    Scanner scanner = new Scanner(file); 

    ArrayList<shortestRoute> arrayList = new ArrayList<shortestRoute>(); 

    while (scanner.hasNextLine()) { 
     String line = scanner.nextLine(); 
     String[] fields = line.split(" "); 

     arrayList.add(new shortestRoute(Integer.parseInt(fields[0]), Integer.parseInt(fields[1]))); 
    } 
    scanner.close(); 

    System.out.println(arrayList); 
} 

我知道查找點到點距離的公式是平方根[(X2-X1)^ 2(Y2-Y1)^ 2]。我遇到的麻煩是將數據點輸入到貪婪算法中。

+0

使用更安全.split(「\\ S +」),將跳過任何數量的你嘗試過什麼到目前爲止與排序的空白字符 – MeBigFatGuy

+0

的?在讀取數據的方式中,我看不出太多問題。您可能需要在arrayList.add函數中進行空檢查。 – kevingreen

+0

你如何計算點到點的距離?它只是'mod(a-b)'? –

回答

0

我認爲這是因爲第一行是文件中的點數。

因爲這是所有的數字只是堅持使用掃描儀。

public static void main(String[] args) throws IOException { 
    File file = new File("output.txt"); 
    Scanner scanner = new Scanner(file); 

    ArrayList<shortestRoute> arrayList = new ArrayList<shortestRoute>(); 

    for(int i =0, n = scanner.nextInt(); i < n; i++) { 
     arrayList.add(new shortestRoute(scanner.nextInt(), scanner.nextInt())); 
    } 
    scanner.close(); 

    System.out.println(arrayList); 
} 
2

您正在使用四個空格拆分輸入字符串。看看輸入文件,我認爲這些數字也可以用製表符分隔。而是使用四個空格,您應該查找任何空格。分裂功能應該像這樣改變:

String[] fields = line.split("\\s+"); 
+0

您有正確的想法,但鑑於'nextLine'確保行結束消耗,您不會遇到奇怪的'nextFoo'錯誤掃描儀未正常推進。 – Makoto

+0

感謝您的意見。編輯我的迴應 – mesbah