All code must be written using C++ programming language. create the method Array
ID: 3858977 • Letter: A
Question
All code must be written using C++ programming language.
create the method ArrayList<GeometricObject> readObjects(string filename). This method will read from the filename passed in, and return a GeometricObject ArrayList with all GeometricObjects from the file in it. Make sure all errors are captured.
Use these classes for the following question:
class GeometricObject {
public String color;
public GeometricObject(String color);
}
class Circle extends GeometricObject {
public double radius;
public Circle(String color, double radius);
}
class Rectangle extends GeometricObject {
public double width, height;
public Rectangle(String color, double width, double height);
}
Use the following file format for storing GeometricObjects:
For Circles:
Circle,Color: (color),Radius: (radius)
For Rectangles:
Rectangle,Color: (color),Width: (width),Height: (height)
Example File:
Circle,Color: Red,Radius: 2.5
Rectangle,Color: Black,Width: 10.0,Height: 20.0
Rectangle,Color: Blue,Width: 5.0,Height: 12.5
Explanation / Answer
public ArrayList<GeometricObject> readObjects(String filename) {
File f = new File(filename);
ArrayList<GeometricObject> al = new ArrayList<GeometricObject>();
try {
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
Scanner s2 = new Scanner(s.nextLine(), “,”);
// type
String type = s2.next();
// color
Scanner s3 = new Scanner(s2.next());
s3.next();
String color = s3.next();
// double1
s3 = new Scanner(s2.next());
s3.next();
double num1 = s3.nextDouble();
GeometricObject go = null;
if (type.equals(“Circle”)) {
go = new Circle(color, num1);
}
else {
s3 = new Scanner(s2.next());
s3.next();
double height = s3.nextDouble();
go = new Rectangle(color, num1, height);
}
al.add(go);
}
} catch (IOException e) {
System.out.println(“Some error reading file”);
}
return al;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.