'How to display a different message for different shapes in an array

This is the code I have been working on.

// array of 6 geometric objects: 2 squares, 2 rectangles, 2 circles
        
GeometricObject[] objects = { new Square(2), new Square(5), new Rectangle(3, 4), new Rectangle(5, 6),
                new Circle(4), new Circle(5)};

        //Display the area by iterating the array's objects.
        for (int i = 0; i < objects.length; i++) {

            System.out.println("Area is " + objects[i].getArea());
            

            //Checking whether or not the object is an instance of interface Colorable.

            if (objects[i] instanceof Colorable) {

                //Invoking the howToColor() method.

                ((Colorable) objects[i]).howToColor();

            }

        }

The current output is this:

Area is 4.0
Color all four sides.
Area is 25.0
Color all four sides.
Area is 12.0
Area is 30.0
Area is 50.26548245743669
Area is 78.53981633974483
4.0
9.0
25.0
36.0
81.0

I want to organize it so it tells you which shape's area its displaying, for example:

The squares area is:
Rectangle area is:
The Circle area is: 

The only time Color all four sides should show up is after the Square's area is displayed. Can someone help me? Thanks!



Solution 1:[1]

You can use the getClass() method. This method will return the class of the object in the form: class ___.

Therefore, we can use a substring to isolate just the class name. Remember, we have to convert the class to a String using String.valueOf():

String className = (String.valueOf(objects[i].getClass()).substring(String.valueOf(objects[i].getClass()).indexOf(" ") + 1));

The purpose of:

String.valueOf(objects[i].getClass()).indexOf(" ")

is to retrieve the index of the space. If we add 1 from here, we get the index of the first letter of the class. Now, we can just take the subtring of String.valueOf(objects[i].getClass() to get our substring.

Now, combining this with your current code:

String className = (String.valueOf(objects[i].getClass()).substring(String.valueOf(objects[i].getClass()).indexOf(" ") + 1));

System.out.println("Area of " + className + " is " + objects[i].getArea());

I hope this helped! Please let me know if you need any further clarification or details :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ani M