Reputation: 3
So basically my teacher wants us to print each shape that is in my ArrayList using this method
for (Shape shape: shapes) {
// this following is the same as: System.out.println(shape.toString());
System.out.println(shape);
}
Which she does not clear up at all so I have no idea what I am supposed to fill in. If anyone knows what she is trying to explain can you show me an example?
I'm not asking to write the code for me just asking for an example so I can get the idea of it.
Thank you for your time everyone.
Full Code
import java.util.ArrayList;
public class FinalExam {
public static void main(String[] args) {
ArrayList<Shape> shapes = new ArrayList<Shape>();
Circle circle5 = new Circle();
circle5.setValues(5.0);
Rectangle square5 = new Rectangle();
square5.setValues(5.0, 5.0);
Triangle triangle5 = new Triangle();
triangle5.setValues(5.0, 5.0);
Circle circle3 = new Circle();
circle3.setValues(3.0);
Rectangle square3 = new Rectangle();
square3.setValues(3.0, 3.0);
Triangle triangle3 = new Triangle();
triangle3.setValues(3.0, 3.0);
shapes.add(circle5);
shapes.add(square5);
shapes.add(triangle5);
shapes.add(circle3);
shapes.add(square3);
shapes.add(triangle3);
}
public void printShapes() {
for (Circle element: Circle) {
// this following is the same as: System.out.println(shape.toString());
System.out.println(element);
}
}
}
Circle class
public class Circle extends Shape {
private double Radius; // To hold Radius.
// Set Radius
public void setValues(double Radius) {
this.Radius = Radius;
}
//Get Radius
public double getRadius() {
return Radius;
}
public double getArea() {
return (Math.PI * Radius *Radius);
}
@Override
public String toString() {
return "Circle" +"[Radius:" + getRadius() + "] Area:" + String.format("%.02f", getArea());
}
}
Upvotes: 0
Views: 90
Reputation: 520968
Here is a corrected version of your FinalExam
class:
public class FinalExam {
public static void main(String[] args) {
ArrayList<Shape> shapes = new ArrayList<Shape>();
// define and add shapes here
printShapes(shapes);
}
public static void printShapes(List<Shape> list) {
for (Shape shape : list) {
System.out.println(shape);
}
}
}
Your syntax to iterate was incorrect, and also I think both methods should be static
(assuming main
is static, and you want to use it). In the above version, I pass the list of shapes to the printing method, but you could also handle this in other ways.
Upvotes: 1