1
import java.util.ArrayList;

public class circleTester {

        public static void showCenter(Circle2 circle) {
            System.out.println(circle.getName() + "'s " + circle.getCenter());
        }

    public static void main (String []args) {

        ArrayList<Circle2> circles = new ArrayList<Circle2>();
        circles.add(new Circle2(3, 5, 4));
        circles.add(new Circle2(4, 2, 5));
        circles.add(new Cylinder2(5, 2, 3, 5));
        circles.add(new Cylinder2(3, 4, 7, 6));
        circles.add(new Oval2(6, 5, 7, 3));
        circles.add(new Oval2(4, 2, 3, 1));
        circles.add(new OvalCylinder2(2, 3, 4, 5, 6));
        circles.add(new OvalCylinder2(3, 3, 5, 4, 7));

        for (Circle2 i : circles) {
            showCenter(circles(i));
        }
      }
    }

I have four separate classes: Circle2, Cylinder2, Oval2, and OvalCylinder2. They're all derived from Circle2, and OvalCylinder2. I'm trying to put them into an array list, and then iterate through the array list and run each instance through the showCenter function, which will call two getter (getName and getCenter) to tell you the class' name (Circle, Cylinder, Oval, and ovalCylinder), and where it's center is (x, y). However, in my for loop, I get an error:

"The method circles(Circle2) is undefined for the type circleTester" How do I fix this?

Ethan Stedman
  • 11
  • 1
  • 6
  • Possible duplicate of [How does the Java 'for each' loop work?](https://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work) – OH GOD SPIDERS Jun 29 '18 at 15:33

2 Answers2

3

Use showCenter(i) instead of showCenter(circles(i)) as i is already an object of Circle2 type

for (Circle2 circle : circles) {
    showCenter(circle);
}
Pramod
  • 1,376
  • 12
  • 21
ctrl-d
  • 392
  • 1
  • 8
0

The syntax foreach loop syntax is:

for (T element : collection) {
  ... 
}

Which reads as "for each T element in collection.". In your case i already has type of Circle2 and can be passed directly to showCenter method.

for (Circle2 circle : circles) {
    showCenter(circle);
}

if you want to iterate over the list using indexes instead:

for (int i = 0; i < circles.size(); i ++) {
        showCenter(circles.get(i));
}

the same can be achieved using an Iterator as well

for (Iterator<Circle2> i = circles.iterator(); i.hasNext(); )
      showCenter(i.next())
} 

and since there is a new forEach method available:

circles.forEach(cicle -> 
                  System.out.println(circle.getName() + "'s " + circle.getCenter()))

which you can combine with labmda expression.

The latest version is arguably preferable if you are using java8+

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53