Java如何为数组元素分配序号 遍历Figure对象时输出对应位置编号
实现方案
核心逻辑是:序号不要定义在Figure类的成员属性中,而是遍历数组时根据元素的当前位置动态生成,这样调整数组元素顺序后,序号也会自动对应最新的位置。
方案1:使用带索引的普通for循环(更直观)
直接通过数组下标计算序号(下标从0开始,序号为下标+1):
Figure[] figures = { createCircle(10), createRectangle(10,20), createSquare(15)}; for (int i = 0; i < figures.length; i++) { Figure f = figures[i]; System.out.println("Figure number " + (i + 1) + ": " + f); }
方案2:保留增强for循环,额外维护计数器
如果你不想修改遍历写法,可以单独定义一个计数器变量记录序号:
Figure[] figures = { createCircle(10), createRectangle(10,20), createSquare(15)}; int sequence = 1; for(Figure f : figures){ System.out.println("Figure number " + sequence + ": " + f); sequence++; }
注意事项
你原有的Figure类及其子类的toString()方法不需要做任何修改,保持输出Circle with a radius of 10.、Rectangle 10x20.这类内容即可,序号会在遍历输出时动态拼接在前面。
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

