简体   繁体   English

如何为数组中的不同形状显示不同的消息

[英]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:现在的output是这样的:

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. Color 所有四个边都应该出现的唯一时间是在显示 Square 的区域之后。 Can someone help me?有人能帮我吗? Thanks!谢谢!

You can use the getClass() method.您可以使用getClass()方法。 This method will return the class of the object in the form: class ___ .此方法将以以下形式返回 object 的 class: class ___

Therefore, we can use a substring to isolate just the class name.因此,我们可以使用 substring 来隔离 class 名称。 Remember, we have to convert the class to a String using String.valueOf() :请记住,我们必须使用String.valueOf()将 class 转换为字符串:

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.如果我们从这里加 1,我们得到 class 的第一个字母的索引。现在,我们可以取String.valueOf(objects[i].getClass()的子串来得到我们的 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 :)我希望这对您有所帮助:如果您需要任何进一步的说明或详细信息,请告诉我 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM