2014-12-07 84 views
0

我试图从1000个条目的文件中读取x,y坐标。凸壳 - 从输入文件中读取

这是我到目前为止有:

int n=4; 
    Point2D []p = new Point2D[n]; 
    p[0] = new Point2D(4,5); 
    p[1] = new Point2D(5,3); 
    p[2] = new Point2D(1,4); 
    p[3] = new Point2D(6,1); 

我可以打开这样的文件:

Scanner numFile = new Scanner(new File("myValues.txt")); 
     ArrayList<Double> p = new ArrayList<Double>(); 
     while (numFile.hasNextLine()) { 
      String line = numFile.nextLine(); 
      Scanner sc = new Scanner(line); 
      sc.useDelimiter(" "); 
      while(sc.hasNextDouble()) { 
       p.add(sc.nextDouble()); 
      } 
      sc.close(); 
     } 
     numFile.close(); 

但我不知道如何与每次两个数值创建阵列。 如果您需要更多信息,请让我知道。

+0

如果您用语言重新标记问题,您将获得更多帮助。它看起来像Java。 – 2014-12-07 18:45:43

回答

0

你真正需要做的是创建一个Point2D对象(使用您的.txt文件的coords)使用在循环的每次迭代中,然后将该对象添加到的Point2D对象的您的数组列表:

例如:

ArrayList<Points2D> p = new ArrayList<>(); 

Scanner numFile = new Scanner(new File("myValues.txt")); 

String pointOnLine = numFile.readLine(); 

while (numFile != null) //if line exists 
{ 

    String[] pointToAdd = pointOnLine.split(" +"); //get x y coords from each line, using a white space delimiter 
    //create point2D object, then add it to the list 
    Point2D pointFromFile = new Point2D(Integer.parseInt(pointToAdd[0]), Integer.parseInt(pointToAdd[1])); 
    p.add(pointFromFile); 
    numFile = numFile.readLine(); //assign numFile to the next line to be read 

} 

棘手的部分(而你在我假设被困的部分),则提取该文件的个别的X和Y坐标。

我上面所做的是使用.split()方法将每一行转换为整行上每个数字的字符串数组,并用空格分隔。由于每行只能包含两个数字(x和y),因此数组大小将为2(分别为元素0和1)。

从那里,我们只需获取字符串数组中的第一个元素(x坐标)和第二个元素(y坐标),然后将这些字符串解析为整数。

现在我们已经将每行的x和y隔开了,我们使用它们来创建Point2D对象,然后将该对象添加到数组列表中。

希望能够澄清事情

+0

非常感谢!这真的帮助了我 – user01230 2014-12-07 19:31:54