[英]Reading Coordinates From A Text File to Loop?
因此,我必须编写一个程序,在其中读取我当前工作目录中文本文件中包含的坐标。 我的问题是在阅读文本文件后,如何使Point对象数组存储这些坐标? 到目前为止,这是我的代码,用于读取文件和while循环。
try {
// create the file reader instance
FileReader fReader = new FileReader(fileName);
// create a scanner to scan through the file
Scanner scan = new Scanner (fReader);
// loop
while (scan.hasNext()) {
int i = 0;
int x = scan.nextInt();
int y = scan.nextInt();
array[i] = new Point(x,y);
i++;
}
// close the reader
fReader.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
如果您不知道要事先阅读多少点,可以使用ArrayList
:
在while循环之前声明并初始化它:
ArrayList<Point> arraylist = new ArrayList<>();
并在循环中使用arraylist.add(point);
给它加一点。
最后,如果您确实需要一个数组,则可以使用以下方法转换ArrayList:
Point[] foo = arraylist.toArray(new Point[arraylist.size()]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.