11

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.

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);
    }
}

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().

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?

3
  • class takes two parameter? Its a class or method.? Commented Mar 2, 2012 at 9:21
  • Its a constructor for the Dog class. See Java Constructors Commented Mar 2, 2012 at 9:22
  • Thanks, your question helped me to get answers! Commented Jan 19, 2022 at 6:50

3 Answers 3

28

Just use it in the for each

for(Dog d : kennel) {
    d.bark();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Haha. You sir are a legend. A class can be a type. Who knew? I guess that explains the creation of the array too. An array of type Dog. Brilliant. Thank you.
10

Here's how you do it using enhanced for loop.

for(Dog dog : kennel) {
    dog.bark();
}

For your other question, if you're going to be using arrays, you'll have to declare the size before you start adding elements to it. One exception, however is if you are doing both initialization and declaration in the same line. For example:

Dog[] dogs = {new Dog("Harold", 1), new Dog("Arnold", 2)};

1 Comment

Thanks brethren! Works like a charm. Although I meant why am I using Dog[] arrayName rather than Foo[] arrayName. You know?
0

About your second question:"Why do I have to start with Dog[] ... new Dog[5]?"

Its because of same logic you have to put Dog dog=new Dog(); ----(1) That's why Dog[] dogArray=new Dog[5]; ---(2)

If you don't have problem with the first one then why crib about the second one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.