增强的for循环 - 对象Array [英] Enhanced For Loop - Array of Objects
问题描述
好了,所以我有一个叫狗(),它有两个参数,一个字符串和一个整数类。
这个类有一个方法叫树皮(),这取决于传入狗()构造函数整数它打印字符串。
Ok so I have a class called Dog() which takes two parameters, a string and an integer.
This class has a method called bark(), which prints a string depending on the integer passed into the Dog() constructor.
我也有))叫做养犬(一类,它创建了5个狗(数组...看起来是这样的:
I also have a class called Kennel() which creates an array of 5 Dog()s... looks like this:
public class Kennel
{
Dog[] kennel = new Dog[5];
public Kennel()
{
kennel[0] = new Dog("Harold",1);
kennel[1] = new Dog("Arnold",2);
kennel[2] = new Dog("Fido",3);
kennel[3] = new Dog("Spot",4);
kennel[4] = new Dog("Rover",5);
}
}
对于新手来说,这个工作,但似乎是错误的。为什么我要开始与狗[] ...新的狗[5]也许愚蠢的问题...我是新来这个。
For starters, this works, but seems wrong. Why do I have to start with Dog[] ... new Dog[5]? Maybe stupid question... I'm new to this.
反正......我被要求做的是使用强化为遍历数组调用树皮迭代()。
Anyway... What I have been asked to do is use the "enhanced" for loop to iterate through the array calling bark().
因此,与传统的for循环就应该是这样的:
So with a traditional for loop it would look like this:
for (i=0;i<kennel.length;i++)
{
kennel[i].bark();
}
简单的东西,对不对?但我怎么使用的(项目类型:数组)实现这个?语法
Simple stuff, right? But how do I implement this using the for(type item : array) syntax?
推荐答案
只是用它在每个
for(Dog d : kennel) {
d.bark();
}
这篇关于增强的for循环 - 对象Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!