0

The array kids is an array of type Infant that has already been declared and initialized with Infant objects. Write a loop that prints, in a column, the names of the all of the infants in the kids array.

This is the Infant class..

public class Infant{

  private  String name;
  private int age;  // in months

  public Infant(String who, int months){
    name = who;
    age = months;
  }

  public String getName(){return name;}

  public int getAge(){return age;}

  public void anotherMonth(){age = age + 1;}
}

The code i have tried is

for (int j = 0; j<kids.length; j++) {

System.out.println(kids.getName());

}
0

2 Answers 2

9

Change your print line statement

System.out.println(kids[j].getName());
0
1

On a side note , another neater way to write the for loop is :

 for (Infant i: kids){

          System.out.println(i.getName());
 }

Which just boils down to, for all infants in the array kids, do a particular operation( in this case print their names)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.