我们已被指派将文本文件转换为几何对象的ArrayList。问题是我不知道我是将它转换为ArrayList还是只是实例化了一个对象? Eclipse声称我还没有使用过ArrayList库
文本文件如下所示:
圈,红色,假的,4.0
圈,蓝色,真实的,2.0
圈,蓝色,真,10.0
矩形,黄色,真实,10.0,6.0
矩形,绿色,真,5.0,11.0
矩形,红色,真实,20.0,15.0
到目前为止,我已使用我的代码执行此操作:
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
GeometricObject g = null;
File diskFile = new File("e:/temp/obj.txt");
Scanner diskScanner = new Scanner(diskFile);
while (diskScanner.hasNext()) {
String list = diskScanner.nextLine();
g = recreateObject(list);
}
diskScanner.close();
}
private static GeometricObject recreateObject(String list) {
String[] data = list.split(",");
String geoObject = data[0];
if (geoObject.equals("Circle")) {
String color = data[1];
boolean filled = Boolean.valueOf(data[2]);
double radius = Double.valueOf(data[3]);
return new Circle(color, filled, radius);
}
if (geoObject.equals("Rectangle")) {
String color = data[1];
boolean filled = Boolean.valueOf(data[2]);
double length = Double.valueOf(data[3]);
double width = Double.valueOf(data[4]);
return new Rectangle(color, filled, length, width);
}
return null;
}
}
我想将每个GeometricObject存储到" ArrayList list = new ArrayList();" [尚未实施]但我不确定该怎么做。
答案 0 :(得分:1)
只需在while循环之外声明ArrayList,然后在循环中添加新对象g ...
List<GeometricObject> geoList = new ArrayList<GeometricObject>();
while(diskScanner.hasNext()){
String list = diskScanner.nextLine();
g = recreateObject(list);
geoList.add(g);
}