| | |
Arrays in Family class
Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Oct 2008
Posts: 24
Reputation:
Solved Threads: 0
Hi, I have a small question regarding arrays. I have the class Family below:
In the constructor for Family(Adult father, Adult mother, Child[] children), I have father, mother (both Adult) and Child[] which is an array of chidren.
The problem is in the main method:
When I run the application this is what I get in the last line
any help on how to modify the code so that it can print out all the family members.
NOTE: Other sections have no problem except this array section.
Java Syntax (Toggle Plain Text)
import java.util.ArrayList; import java.util.Collection; import java.io.*; public class Family { private Adult father; private Adult mother; private Child[] children; private Dog ourDog; private Cats ourCat; private Rabbit ourRabbit; int Age; public Family() { } public Family(Adult father, Adult mother, Child[] children) { setFather(father); setMother(mother); setChildren(children); ourDog=new Dog(""); ourCat=new Cats(""); ourRabbit = new Rabbit(""); } private Adult getFather() { return this.father; } private Adult getMother() { return this.mother; } private Child[] getChildren() { return this.children; } private void setFather(Adult father) { this.father = father; } private void setMother(Adult mother) { this.mother = mother; } private void setChildren(Child[] children) { this.children = children; } public Collection getMovieGoers(int rating) { ArrayList mGoers = new ArrayList(); // I consider rating here to be the starting age that is allowed for the movie if ( father.getAge() >= rating) mGoers.add(father); if ( mother.getAge() >= rating) mGoers.add(mother); for(int i = 0; i < children.length; i++) { if (children[i].getAge() >= rating) mGoers.add(children[i]); } return mGoers; } public static void main(String args[])throws IOException { MovieRating mRt = new MovieRating(); Child[] children = {new Child("Frank",10), new Child("Lisa",18)}; Family fam = new Family(new Adult("John",37), new Adult("Mary",35),children); ArrayList mvGoers= (ArrayList)fam.getMovieGoers(mRt.getAdult()); System.out.println("Movie goers: "+mvGoers+""); //pets fam.ourCat.catType("Angora"); fam.ourCat.setCatColor("Brownish white"); fam.ourDog.dogType("African Shepherd Dog"); fam.ourDog.setDogColor("Black"); fam.ourRabbit.setRabbitColor("White"); fam.ourRabbit.rabbitType("Akorino"); System.out.println("We own the following pets: " + " " + fam.ourDog.MydogType+ " " + fam.ourDog.dog_color + " in color;" + " a small " + fam.ourCat.cat_color + " " +fam.ourCat.MyCatType+ " cat;"+ " and a "+ fam.ourRabbit.rabbit_color +" "+ fam.ourRabbit.MyRabbitType + " rabbit."); } }
In the constructor for Family(Adult father, Adult mother, Child[] children), I have father, mother (both Adult) and Child[] which is an array of chidren.
The problem is in the main method:
Java Syntax (Toggle Plain Text)
Child[] children = {new Child("Frank",10), new Child("Lisa",18)}; Family fam = new Family(new Adult("John",37), new Adult("Mary",35),children); ArrayList mvGoers= (ArrayList)fam.getMovieGoers(mRt.getAdult()); System.out.println("Movie goers: "+mvGoers+"");
When I run the application this is what I get in the last line
Java Syntax (Toggle Plain Text)
Movie goers: [myinheritancepolymorph.Adult@1a46e30, myinheritancepolymorph.Adult@3e25a5]
any help on how to modify the code so that it can print out all the family members.
NOTE: Other sections have no problem except this array section.
Whenever in need of a sane string representation of your instance, override the
toString() method for the given class. This makes sure that each class is responsible for giving out its own representation without having to write the same temporary code again and again. For pretty printing arrays, convert them first to a list using Arrays.asList(yourArray) . Java Syntax (Toggle Plain Text)
public class Family { private Adult father; private Adult mother; private Child[] children; public String toString() { StringBuilder buf = new StringBuilder(256); buf.append("Father {").append(father) .append("} Mother {").append(mother) .append("} Children {").append(Arrays.asList(children)) .append("}"); return buf.toString(); } } public class Adult { private String name; // other instance variables go here public String toString() { StringBuilder buf = new StringBuilder(128); buf.append("Name: ").append(name); return buf.toString(); } }
I don't accept change; I don't deserve to live.
•
•
Join Date: Oct 2008
Posts: 24
Reputation:
Solved Threads: 0
•
•
•
•
Whenever in need of a sane string representation of your instance, override thetoString()method for the given class. This makes sure that each class is responsible for giving out its own representation without having to write the same temporary code again and again. For pretty printing arrays, convert them first to a list usingArrays.asList(yourArray).
Java Syntax (Toggle Plain Text)
public class Family { private Adult father; private Adult mother; private Child[] children; public String toString() { StringBuilder buf = new StringBuilder(256); buf.append("Father {").append(father) .append("} Mother {").append(mother) .append("} Children {").append(Arrays.asList(children)) .append("}"); return buf.toString(); } } public class Adult { private String name; // other instance variables go here public String toString() { StringBuilder buf = new StringBuilder(128); buf.append("Name: ").append(name); return buf.toString(); } }
Java Syntax (Toggle Plain Text)
Child[] children = {new Child("Frank",10), new Child("Lisa",18)}; Family fam = new Family(new Adult("John",37), new Adult("Mary",35),children); ArrayList mvGoers= (ArrayList)fam.getMovieGoers(mRt.getAdult()); System.out.println("Movie goers: "+mvGoers+"");
to get an output like this:
Movie goers: [John , Mary, Frank, Lisa]
as in the names of Adult and Child given.
> aah! its seems we're not communicating! You are complicating the code further
Yes, rightly said, because it is what you asked for in the first place. Re-read your first post:
> NOTE: Other sections have no problem except this array section.
There is no `array section' here; it is how the
There are two ways of doing it; either the way mentioned in my first post or writing a method which takes the
Yes, rightly said, because it is what you asked for in the first place. Re-read your first post:
•
•
•
•
any help on how to modify the code so that it can print out all the family members.
There is no `array section' here; it is how the
toString() to the ArrayList class is implemented.There are two ways of doing it; either the way mentioned in my first post or writing a method which takes the
List , loops over it and extracts the name, either printing them or adding them again to a new List which then gets displayed. I don't accept change; I don't deserve to live.
•
•
•
•
to get an output like this:
Movie goers: [John , Mary, Frank, Lisa]
as in the names of Adult and Child given.
since your Family class does not have such a method, you'll just see a String representation of the memory-address used by the Object. if you want to make a print-out of all the persons' names in the list, the best way to do so is by creating that toString method.
•
•
Join Date: Oct 2008
Posts: 24
Reputation:
Solved Threads: 0
thanks, i've corrected it.
I have another problem with a List in a class called Mammal. The code is like this:
How do I instatiate the limbs list?
Since in my implemetetion above my tutor tells me that I can't call its add() method
- You are trying to cast a List into a Limb. this cant work.
I have another problem with a List in a class called Mammal. The code is like this:
Java Syntax (Toggle Plain Text)
import java.util.*; public abstract class Mammal { Head head; char gender; public String name; protected int age = 0; private List <Limb> limbs; String myArm,myLeg; protected Mammal() { this.limbs = new ArrayList<Limb>(); limbs.add(new Leg("Left")); limbs.add(new Leg("Right")); limbs.add(new Arms("Left")); limbs.add(new Arms("Right")); } protected Mammal(List<Limb> limbs) { this.limbs = limbs; } // adding limbs: protected void addLimbs(List<Limb>limbToAdd) { this.limbs.add((Limb) limbToAdd); } //remove limbs protected void removeLimbs(List<Limb> limbToRemove) { Object temp = null; Iterator iter = limbs.iterator(); while (iter.hasNext()) { temp = iter.next(); if (temp instanceof Arms) { //myArm = (Arms)temp; iter.remove(); // iter.remove(myArm); if (temp instanceof Leg) { //myLeg = (Leg)temp; iter.remove(); //iter.remove(myLeg); } } } } protected List<Limb> getLimbs() { return this.limbs; } public Mammal(String name) { this.name = name; } public void getOlder(int years) { age += years; } public void makeSound() { System.out.print(name+" Oooops "); } public void eat() { System.out.print("Some food please..."); } }
How do I instatiate the limbs list?
Since in my implemetetion above my tutor tells me that I can't call its add() method
- You are trying to cast a List into a Limb. this cant work.
Java Syntax (Toggle Plain Text)
// adding limbs: protected void addLimbs(List<Limb>limbToAdd) { this.limbs.add((Limb) limbToAdd); }
> - You are trying to cast a List into a Limb. this cant work.
Yes, it's true; look at my previous post for the answer.
> You have not instatiated the limbs list, how can you then call its add() method
This comment seems weird since you have instantiated the `
BTW, your implementation of
Yes, it's true; look at my previous post for the answer.
> You have not instatiated the limbs list, how can you then call its add() method
This comment seems weird since you have instantiated the `
limbs ' list in the Mammal constructor.BTW, your implementation of
removeLimbs is broken. Why do you require instanceof checks? Plus, those nested IF blocks are incorrect. You could have simply done a limbs.clear() and got away with it. I don't accept change; I don't deserve to live.
![]() |
Similar Threads
- Parsing html form. (PHP)
- PHP codes to search MySQL (PHP)
- Inventory part 6 (Java)
- Inventory part 5 (Java)
- Javascript array from sql query (JSP)
- Import/export tab delimited file (PHP)
- look-up table help (PHP)
- Form not sending email (PHP)
Other Threads in the Java Forum
- Previous Thread: <identifier> expected? Pls help my code!
- Next Thread: Creating methods with Scenarios
| Thread Tools | Search this Thread |
911 actionlistener addressbook android api append applet application array arrays automation binary block bluetooth character chat class client code component consumer csv database desktop eclipse error fractal ftp game givemetehcodez graphics gui html ide image input integer j2me japplet java javaarraylist javac javaee javaprojects jmf jni jpanel julia linked linux list loop mac map method methods mobile netbeans newbie number objects online oriented panel print printf problem program programming project projects properties recursion replaydirector reporting researchinmotion rotatetext rsa scanner screen se server set size sms sort sql string swing template test threads time title tree tutorial-sample ubuntu update windows working






