Results 1 to 18 of 18
Thread: Having a problem with Java...
- 05-20-2010, 03:32 AM #1
Member
- Join Date
- May 2010
- Posts
- 6
- Rep Power
- 0
Having a problem with Java...
Hi there.
I apologize in advance for a long post.
Here is the problem:
I need to add the new Member to ArrayList using addMember method (in Process.java file) and then loop through and write them to a file using different method.
I am not sure if addMember inside Process.java is correct since I am passing different member types to it and want to call specific methods from these member classes, but method accepts Member type only.
For example in Main.java I create new InsuranceMember and pass it to addMember method in Process.java, but addMember looks like this: addMember(Member myMember), so myMember will have only methods from Member class available, but not from InsuranceMember.
The files:
Member.java
InsuranceMember.java
SpecialMember.java
LifeMember.java
Process.java
Member (attributes: name, address,membershipNo)
InsuranceMember is a type of Member (attributes: monthlyFee 300, joinFee 150)
Special Member is a type of Member (attributes: monthlyFee 50)
LifeMember is a type of SpecialMember (attributes: fee 12 times SpecialMember's monthly fee)
Here is the code:
Member.java
InsuranceMember.javaPHP Code:public class Member { private String type; private String name; private String address; private int membershipNo; public Member(String myType, String myName, String myAddress, int myMembershipNo) { type = myType; name = myName; address = myAddress; membershipNo = myMembershipNo; } }
PHP Code:public class InsuranceMember extends Member { private int monthlyFee; /** * */ public InsuranceMember(String type, String name, String address, int membershipNo) { super(type, name, address, membershipNo); monthlyFee = 50; } }
SpecialMember.java
LifeMember.javaPHP Code:public class SpecialMember extends Member { private int monthlyFee; private int joinFee; /** * */ public SpecialMember(String type, String name, String address, int membershipNo) { super(type, name, address, membershipNo); monthlyFee = 300; joinFee = 150; } public int getJoiningFee() { return joinFee; } }
Main.javaPHP Code:public class LifeMember extends SpecialMember { private double lJoiningFee; public LifeMember(String type, String name, String address, int membershipNo) { super(type, name, address, membershipNo); lJoiningFee = super.getJoiningFee()*12; } }
Process.javaPHP Code:public class Main { public Main() { } public static void main(String[] args) { Process p = new Process(); InsuranceMember im = new InsuranceMember("InsuranceMember", "Name", "Address", 1234); SpecialMember sm = new SpecialMember("SpecialMember", "Name", "Address", 1234); p.addMember(im); p.addMember(sm); } }
PHP Code:public class Process { private ArrayList members; public Process() { } // Is there a way to receive public void addMember(Member myMember) { members.add(myMember); } public writeToFile { // Loop through ArrayList or Vector and write to a file } }Last edited by sek; 05-20-2010 at 04:23 AM.
- 05-20-2010, 03:38 AM #2
Senior Member
- Join Date
- Mar 2010
- Posts
- 953
- Rep Power
- 4
Presuming you want a collection of all Members, no matter what subclass, you are doing it correctly.
Not true, but you may need a cast. Show us some code that wants to call subclass methods, and we can probably help you out with how to get that done.
-Gary-
- 05-20-2010, 03:45 AM #3
Senior Member
- Join Date
- May 2010
- Posts
- 436
- Rep Power
- 4
It looks good to me. Even though you are often adding objects that are subclasses of Member, they still nevertheless are Member objects, and so this should work fine. You may have to override toString in Member and the subclasses to have each object write its data to file. Or consider using serialization.
You may wish to check that the class name matches the constructor name here.InsuranceMember.java
Java Code:public class InsuranceMember extends Member { private int monthlyFee; // ****** [color="red"]Special[/color]Member ???? ****** public SpecialMember(String type, String name, String address, int membershipNo) { super(type, name, address, membershipNo); monthlyFee = 50; } }
- 05-20-2010, 04:35 AM #4
Member
- Join Date
- May 2010
- Posts
- 6
- Rep Power
- 0
Thanks for reply.
Yes I want a collection of all Members, no matter what subclass, but how can I access let's say getJoiningFee() method (available in SpecialMember class) inside addMember method or inside writeToFile method when I want to save it.
Something like:
or to pass ArrayList members to this method, loop through arraylist and display member's detailsPHP Code:public void addMember(Member myMember) { members.add(myMember); myMember.getJoiningFee(); }
Maybe my logic is wrong?PHP Code:public void writeToFile() { // Loop through ArrayList or Vector and write to a file or print to the screen }
Thanks
Sorry, I fixed that. That was my copy->paste error. Tried to cut down the code to a min, so it's easier to read.Last edited by sek; 05-20-2010 at 04:38 AM.
- 05-20-2010, 06:29 AM #5
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
For your problem, you should look into the instanceof command. It tells you, if a variable declared as a superclass is actually a subclass. Example:
Java Code:class Person { //bla bla } class Worker extends Person { //bla bla public void doWork() {} //Worker method, not found in Person } class Test { public static void main(String[] args) { Person p = new Worker(); if(p instanceof Worker) { Worker w = (Worker) p; w.doWork(); } } }Ever seen a dog chase its tail? Now that's an infinite loop.
- 05-21-2010, 01:30 AM #6
Member
- Join Date
- May 2010
- Posts
- 6
- Rep Power
- 0
Thanks for that, it worked beautifully.
I have one more question though.
How to loop through ArrayList that holds Member objects and write their details to a file?
Need help with getting their details out from that loop below.
Here is an example what I am trying to do:
PHP Code:public void writeToFile(ArrayList members) { for(Iterator i = members.iterator();i.hasNext();) { //How to get Member's details here? } }
- 05-21-2010, 01:50 AM #7
Senior Member
- Join Date
- May 2010
- Posts
- 436
- Rep Power
- 4
instanceOf definitely has its uses, but you don't want to over-rely on it as that suggests possible bad design. For instance, your writeToFile shouldn't require this as each class should probably know how they should be written to file and this could probably be abstracted into the base class with a method that is overridden by tht child classes.
- 05-21-2010, 09:39 AM #8
an easy solution to write objects to a file is to serialize the arraylist and the objects in it. i didn't analyze your classes but here is an example i used for a book library.
Java Code:// this class holds the arraylist and must be serializable public class MyLibrary implements Serializable { ArrayList<Book> myLibrary = new ArrayList<Book>(); //other code ...
Java Code:// the objects in the arraylist must also be serializable public class Book implements Serializable { //other code ...
now to write all the books stored in the library i used the following code
Java Code:public static void saveLibrary(MyLibrary myLib) { try { File file = new File("library.ser"); FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream out = new ObjectOutputStream(fos); out.writeObject(myLib); } catch (IOException ex) { ex.printStackTrace(); } }
and to retrieve the book from the library i used
Java Code:public static MyLibrary readLibrary() { MyLibrary myLib = null; try { File file = new File("library.ser"); FileInputStream fos = new FileInputStream(file); ObjectInputStream in = new ObjectInputStream(fos); myLib = (MyLibrary) in.readObject(); } catch (Exception ex) { ex.printStackTrace(); } return myLib; }
you can surely find an analogy to your code. so you don't have to loop through your arraylist, instead you can save all your stuff at once.
- 05-21-2010, 10:27 AM #9
Moderator
- Join Date
- Apr 2009
- Posts
- 10,460
- Rep Power
- 16
As already mentioned, the subclasses themselves should have a method that takes a PrintWriter to allow themselves to write themselves out. I say that rather than a straight writeToFile() method since you may not want this to write to a different file from other objects in your system.
For the loop, you want to declare (as j2me64 does in his example) your ArrayList as ArrayList<Member>. This means that the above loop would be:
Java Code:for (Iterator<Member> i = members.iterator(); i.hasNext(); ) { Member member = i.next(); }
- 05-21-2010, 10:31 AM #10
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
Right on the money there. I did want to add in another example, but forgot about it, it deals exactely with what you wrote.
Even though the variable c is defined as Class1, the output will be Class2. Design like this can really ease the use of subclasses in a collection that holds objects of the superclass type.Java Code:public class Class1 { public void doSomething() { System.out.println("Class1"); } } public class Class2 extends Class1 { public void doSomething() { //override System.out.println("Class2"); } } public class Test { public static void main(String[] args) { Class1 c = new Class2(); c.doSomething(); } }
And to Tolls:
Using for loops with iterators has always been a pet peeve of mine. I much prefer a while loop. It is only a choice of style, since the functionality is the same, I just feel it looks cleaner like this:
Java Code:Iterator i = someCollection.iterator(); while(i.hasNext()) { //do something }Last edited by m00nchile; 05-21-2010 at 10:34 AM.
Ever seen a dog chase its tail? Now that's an infinite loop.
- 05-21-2010, 02:34 PM #11
Senior Member
- Join Date
- Mar 2010
- Posts
- 953
- Rep Power
- 4
And with Java 5 or later, you can use the even nicer "for each" style:
which in this case would be something likeJava Code:for (ObjectType currentObject : someCollection) { // do something }
-Gary-Java Code:for (Member member : members) { // do something with member }
- 05-21-2010, 02:38 PM #12
Moderator
- Join Date
- Apr 2009
- Posts
- 10,460
- Rep Power
- 16
- 05-22-2010, 12:03 PM #13
Member
- Join Date
- May 2010
- Posts
- 6
- Rep Power
- 0
Thanks guys, much appreciated!
I will give these a go and see what happens (and probably come back with more questions :o ).
- 05-22-2010, 12:36 PM #14
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
- 05-29-2010, 04:00 PM #15
Member
- Join Date
- May 2010
- Posts
- 6
- Rep Power
- 0
Thanks all for help, I've figured it out with your examples.
However, how can I replace objects in ArrayList. I am trying to update scores (int array with five elements) for SpecialMember, but whatever I do, it gets all overwritten with the last record score. Here is the code.
this is how it looks like when ran:PHP Code:for (int intIndex = 0; intIndex < members.size(); intIndex++) { Member member = (members.get(intIndex)); if (member instanceof SpecialMember) { // Get array of old scores oldScores = ((SpecialMember) member).getScores(); System.out.println("\nPlease enter new score: "); newScore = inScore.nextInt(); if (newScore > 0) { // Make a copy of array with last four scores System.arraycopy(oldScores, 1, newScores, 0, 4); // Add last entered score to existing scores newScores[4] = newScore; // Create new object with new scores SpecialMember pm2 = new SpecialMember(memberType, memberName, memberAddress, membershipNo, newScores); System.out.println("New scores: " + Arrays.toString(newScores)); // Update object in ArrayList members.set(intIndex, pm2); }
name1 adress1 22 33 44 55 66
Please enter new score:
I enter 91
New scores: 33 44 55 66 91
name2 address2 99 88 77 66 55
Please enter new score:
I enter 81
New scores: 88 77 66 55 81
name3 address3 55 33 77 99 11
Please enter new score:
I enter 71
New scores: 33 77 99 11 71
and after that the ArrayList members looks like this:
name1 adress1 33 77 99 11 71
name2 address2 33 77 99 11 71
name3 address3 33 77 99 11 71
I've spent literally almost 2 days trying to figure out this and nothing :mad:Last edited by sek; 05-29-2010 at 04:13 PM.
- 05-29-2010, 04:08 PM #16
Senior Member
- Join Date
- May 2010
- Posts
- 436
- Rep Power
- 4
It looks like you're using the same newScores array object for all of your SpecialMember objects. Myself I'd use an ArrayList to hold the scores rather than increasing the array size and copying over, but regardless if you use an array for this or an ArrayList, the new collection needs to be created anew from within the for loop. In otherwords, if you're using an array and it's called newScores, you need to recreate this array within this for loop else you'll keep reusing the same object in all Members.
- 05-29-2010, 04:23 PM #17
Member
- Join Date
- May 2010
- Posts
- 6
- Rep Power
- 0
- 05-29-2010, 04:28 PM #18
Senior Member
- Join Date
- May 2010
- Posts
- 436
- Rep Power
- 4
Similar Threads
-
java problem
By Mj Shine in forum New To JavaReplies: 5Last Post: 08-15-2009, 05:09 AM -
Help, java problem
By Suriman in forum New To JavaReplies: 4Last Post: 03-09-2009, 04:26 PM -
JAVA and XML Problem
By jackchang in forum XMLReplies: 4Last Post: 02-22-2009, 08:28 PM -
Java problem
By grend in forum New To JavaReplies: 5Last Post: 08-18-2008, 11:44 PM -
java SE 6 problem
By techlance in forum Java AppletsReplies: 1Last Post: 06-28-2007, 10:10 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks