Results 1 to 18 of 18
  1. #1
    sek
    sek is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default 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
    PHP 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;
    	}
    }
    InsuranceMember.java
    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
    PHP 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;
    	}
    }
    LifeMember.java
    PHP 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;
    	}
    }
    Main.java
    PHP 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);
    }
    }
    Process.java
    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.

  2. #2
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by sek View Post
    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.
    Presuming you want a collection of all Members, no matter what subclass, you are doing it correctly.
    Quote Originally Posted by sek View Post
    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.
    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-

  3. #3
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by sek View Post
    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.
    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.

    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;
    	}
    }
    You may wish to check that the class name matches the constructor name here.

  4. #4
    sek
    sek is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default

    Quote Originally Posted by gcalvin View Post
    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-
    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:
    PHP Code:
    public void addMember(Member myMember) {
            members.add(myMember);
            myMember.getJoiningFee();
    }
    or to pass ArrayList members to this method, loop through arraylist and display member's details
    PHP Code:
    public void writeToFile() {
    // Loop through ArrayList or Vector and write to a file or print to the screen
    }
    Maybe my logic is wrong?

    Quote Originally Posted by curmudgeon View Post
    You may wish to check that the class name matches the constructor name here.
    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.

  5. #5
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    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.

  6. #6
    sek
    sek is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default

    Quote Originally Posted by m00nchile View Post
    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();
        }
      }
    }
    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?
    		}
    	 }

  7. #7
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    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.

  8. #8
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    6

    Default

    Quote Originally Posted by sek View Post
    How to loop through ArrayList that holds Member objects and write their details to a file?

    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.

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,036
    Rep Power
    20

    Default

    Quote Originally Posted by sek View Post
    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?
    		}
    	 }
    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();
    }

  10. #10
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Quote Originally Posted by curmudgeon View Post
    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.
    Right on the money there. I did want to add in another example, but forgot about it, it deals exactely with what you wrote.
    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();
      }
    }
    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.
    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.

  11. #11
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by m00nchile View Post
    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
    }
    And with Java 5 or later, you can use the even nicer "for each" style:
    Java Code:
            for (ObjectType currentObject : someCollection) {
                    // do something
            }
    which in this case would be something like
    Java Code:
            for (Member member : members) {
                    // do something with member
            }
    -Gary-

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,036
    Rep Power
    20

    Default

    Quote Originally Posted by m00nchile View Post
    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
    }
    Oh yes, quite agree.
    I was merely rewriting the OPs code with the bare minimum of changes.
    Otherwise I would have written the for-each version...in fact I did start writing that, but felt it was one less thing to explain if I simply showed generics.

  13. #13
    sek
    sek is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default

    Thanks guys, much appreciated!
    I will give these a go and see what happens (and probably come back with more questions :o ).

  14. #14
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Quote Originally Posted by Tolls View Post
    Oh yes, quite agree.
    I was merely rewriting the OPs code with the bare minimum of changes.
    Otherwise I would have written the for-each version...in fact I did start writing that, but felt it was one less thing to explain if I simply showed generics.
    Yeah, I must say that the for each loop hasn't dug into my mind yet, although it's an even better solution than the while loop, since you don't have to declare the iterator, makes the code even more clean.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  15. #15
    sek
    sek is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default

    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.

    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);
    			}
    this is how it looks like when ran:

    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.

  16. #16
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    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.

  17. #17
    sek
    sek is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default

    Quote Originally Posted by curmudgeon View Post
    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.
    Thanks a lot man!
    That was exactly what it was. After I recreated newScores array inside the loop instead of above everything worked.

    Much appreciated, thanks again.

  18. #18
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by sek View Post
    Thanks a lot man!
    That was exactly what it was. After I recreated newScores array inside the loop instead of above everything worked.
    Much appreciated, thanks again.
    You're welcome, and glad it helped!

Similar Threads

  1. java problem
    By Mj Shine in forum New To Java
    Replies: 5
    Last Post: 08-15-2009, 05:09 AM
  2. Help, java problem
    By Suriman in forum New To Java
    Replies: 4
    Last Post: 03-09-2009, 04:26 PM
  3. JAVA and XML Problem
    By jackchang in forum XML
    Replies: 4
    Last Post: 02-22-2009, 08:28 PM
  4. Java problem
    By grend in forum New To Java
    Replies: 5
    Last Post: 08-18-2008, 11:44 PM
  5. java SE 6 problem
    By techlance in forum Java Applets
    Replies: 1
    Last Post: 06-28-2007, 10:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •