我正在尝试从包含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 :(得分: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对象,然后将该对象添加到数组列表中。
希望这能澄清事情