12 Replies - 1580 Views - Last Post: 08 April 2012 - 11:47 AM Rate Topic: -----

#1 menace12  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 06-April 12

Add, Get number, return methods from class - Beginner at Java...

Posted 06 April 2012 - 05:01 AM

Hi there, I'm new to JAVA programming and would like to ask a few questions regarding a database i'm constructing for a gym membership. I currently have a class called activity with the following code I have put in:
public class Activity {
 String name ="";

    public Activity(String name) {
        this.name = name;
    }

    public String getName() {
         return name;
    }
}



I'm trying to create methods used in a module called GymBase which are below:

public class GymBase implements IGymBase {
    String act;
   /**
     * Add an activity to the database.
     * @param activity The name of the activity to add.
     */[/color]
    public void addActivity(String activity) {
      Activity act = new Activity("activity");
    }
    /**
     * Get the number of activities in the database.
     * @return Number of activities in the database.
     */[/color]
    public int getNbrActivities() {
              return 0;
    }

    /**
     * Get the i'th activity in the database.
     * @param i Index of the activity (indices start at 0).
     * @return The name of the activity.
     */[/color]
    public String getActivity(int i) {
      return act.getName(i);
          }

    /**


So far I have put in the methods for getActivity and addActivity, but neither are working...Can anyone point me in the right direction? There are other parts of the database such as a GUI and Main.java, however they are created in a way which means i don't need to edit them.

Any help is appreciated.

Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: Add, Get number, return methods from class - Beginner at Java...

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2194
  • View blog
  • Posts: 5,222
  • Joined: 10-September 10

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 06 April 2012 - 05:17 AM

Describing what "not working" means to you so that we can understand what "working" means is always helpful. We don't know what either mean at this point and any help offered would only be guessing at the desired outcome. For example, the following addActivity() method
public void addActivity(String activity)
{  
    Activity act = new Activity("activity");  
}

looks correct if you want every new activity to actually be named 'activity' rather than the name passed to the method in the variable named activity. If you wanted to use the name passed to the method, the statement would be:

Activity act = new Activity( activity );

But is that what's "not working?" I don't know. Perhaps you could be more specific.

It would also be helpful, but maybe not essential, to know what IGymBase is.
Was This Post Helpful? 0
  • +
  • -

#3 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 202
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 06 April 2012 - 05:25 AM

Ok, let's go this step by step. Your activity class is looking how it should look, so that's not a real problem. Now lets consider your addActvitiy:

   /**
     * Add an activity to the database.
     * @param activity The name of the activity to add.
     */[/color] //<---- Why is this here?
    public void addActivity(String activity) {
      Activity act = new Activity("activity");
    }



As you can see, the addActivity is flawed in two manners, namely:
- First, you do not use the String activity to instantiate an activity. Each time you call on addActivity("mystring") (for example) an object with the string value "activity" is created
- Second, the method itself does not add the activity to a datastructure. What kind of data structure are you using to store items? You're just stating Activity act = new Activity("activity") without doing anything with it. For example, you don't add it in some kind of database or datastructure.

So, think of what kind of datastructure you have or would use to store activities in the gymbase. Next change your code:

   /**
     * Add an activity to the database.
     * @param activity The name of the activity to add.
     */
    public void addActivity(String activity) {
      Activity act = new Activity(activity); //I removed the parenthesis (") as I do not want to instantiate an activity object with the value "activity" but with a value given by the argument of the method (which is activity)
     
     //Add the activity to the datastructure
     activities.add(act); //The exact code depends on the datastructure you'll use
    }



Next, the getActivity method. So you want to get the activity name at the i'th entry of the database (or datastructure in this context)
Now think of few things before you proceed:

- What should happen if i is negative, or better said:
- What should happen if i is outside the bounds of the datastructure (suppose I have n items and i = n + 1 for example)

You need to (though, it is not mandatory, but highly advisable) check the validity of i. Then, in pseudocode:

public String getActivity(int i){
  //Do check and return what ever you like if i fails the test You could also throw an exception for example  

 //Get the activity item at position i of your datastructure
 Activity temp = activities.get(i); //Actual code depends on your datastructure
 
  //Return the name of the activity
  return temp.getName();
}



Although, I have to admit, that this is just guessing. As I do not know what your interface IGymBase is, I cannot post an adequate solution for your problem.

Good luck! ^^

This post has been edited by karabasf: 06 April 2012 - 05:31 AM

Was This Post Helpful? 1
  • +
  • -

#4 menace12  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 06-April 12

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 06 April 2012 - 05:41 AM

View PostGregBrannon, on 06 April 2012 - 05:17 AM, said:

Describing what "not working" means to you so that we can understand what "working" means is always helpful. We don't know what either mean at this point and any help offered would only be guessing at the desired outcome. For example, the following addActivity() method
public void addActivity(String activity)
{  
    Activity act = new Activity("activity");  
}

looks correct if you want every new activity to actually be named 'activity' rather than the name passed to the method in the variable named activity. If you wanted to use the name passed to the method, the statement would be:

Activity act = new Activity( activity );

But is that what's "not working?" I don't know. Perhaps you could be more specific.

It would also be helpful, but maybe not essential, to know what IGymBase is.


Apologies for not explaining it correctly. It's quite hard to explain without showing all of the coding. My task is to basically create a variety of methods using two separate classes known as activity and member. The example i showed in my first post is a method that is required to add an activity on the basis of what is typed in. The other methods are methods which find number of activities entered, enrol a member to that activity etc. The GUI and Main.java modules have been created already and are not to be edited. My task is to implement the sort of methods described earlier in a another JAVA file called GymBase. So there are 5 separate java files:

Activity.java
public class Activity {
 String name ="";

    public Activity(String name) {
        this.name = name;
    }

    public String getName() {
         return name;
    }
}


Member.Java
public class Member {
    String firstName;
    String lastName;

    public Member(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName(){
       return firstName;
    }

    public String getLastName(){
        return lastName;
    }

    public String getFullName(){
        return firstName + lastName;
    }
}


GymBase.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class GymBase implements IGymBase {
        /**
     * Add an activity to the database.
     * @param activity The name of the activity to add.
     */
    public void addActivity(String activity) {
      Activity act = new Activity(activity);
    }
    /**
     * Get the number of activities in the database.
     * @return Number of activities in the database.
     */
    public int getNbrActivities() {
              return 0;
    }

    /**
     * Get the i'th activity in the database.
     * @param i Index of the activity (indices start at 0).
     * @return The name of the activity.
     */
    public String getActivity(int i) {
      return act.getName(i);
          }

    /**
     * Add an member to the database.
     * @param firstName First name of the member.
     * @param lastName Last name of the member.
     */
    public void addMember(String firstName, String lastName) {
    }

    /**
     * Get the number of members in the database.
     * @return Number of members in the database.
     */
    public int getNbrMembers() {
        return 0;
    }

    /**
     * Get the full i'th member in the database.
     * @param i Index of the member (indices start at 0).
     * @return The full name of the member.
     */
    public String getMember(int i) {
        return null;
    }

    /**
     * Get the first name of the i'th member in the database.
     * @param i Index of the member (indices start at 0).
     * @return The first name of the member.
     */
    public String getMemberFirstName(int i) {
        return null;
    }

    /**
     * Get the last name of the i'th member in the database.
     * @param i Index of the member (indices start at 0).
     * @return The last name of the member.
     */
    public String getMemberLastName(int i) {
       return null;
    }


    /**
     * Enrol a member on an activity.
     * The member and activity must already be present in the database. The member 
     * must not be already be enrolled on the activity.
     * @param activityName The name of the activity.
     * @param firstName The first name of the member.
     * @param lastName The last name of the member.
     * @return true if the member was successfully enrolled on of the 
     * activity (this happens if the activity and member are already in the database,
     * and the member has not already been enrolled on the activity.
     */
    public boolean addMemberToActivity(String activityName,String firstName,
                                                  String lastName){
        
        return false;
    }

    /**
     * Get the number of members enrolled on an activity
     * @param activityName The name of the activity.
     * @return The number of members enrolled on this activity.
     */
    public int getNbrMembersForActivity(String activityName) {
        return 0;
    }

    /**
     * Get the i'th member enrolled on a particular activity.
     * @param activityName The name of the activity.
     * @param i Index of the member (indices start at 0). Note that this is the
     * index of the member within this particular activity, not the index of the 
     * member in the database.
     * @return The full name of the member.
     */
    public String getMemberForActivity(String activityName, int i) {
        return null;
    }

    /**
     * Get the number of activities that an member is enrolled on.
     * 
     * @param firstName First name of the member.
     * @param lastName Last name of the member.
     * @return The number of activities that the member is enrolled on.
     */
    public int getNbrActivitiesForMember(String firstName, String lastName) {
        return 0;
    }


    /**
     * Get the i'th activity that an member is enrolled on.
     * @param firstName First name of the member.
     * @param lastName Last name of the member.
     * @param i Index of the activity (indices start at 0). Note that this is the
     * index of the activity within the list associated with this particular member,
     * not the index of the activity in the database.
     * @return The name of the activity
     */
    public String getActivityForMember(String firstName, String lastName, int i) {
        return null;
    }

    /**
     * Save the database to a file.
     * 
     * @param fileName name of the file to save to.
     * @throws FileNotFoundException
     */
    public void save(String fileName) throws FileNotFoundException {
    }

    /**
     * Load the database from a file.
     * @param fileName Name of the file to load from.
     * @throws FileNotFoundException
     */
    public void load(String fileName) throws FileNotFoundException {
    }
}



Main.java


//package gymbase;

import java.io.FileNotFoundException;
import java.util.Scanner;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author p0073862
 */
public class Main {


    private static GymBase gymBase = new GymBase();
    private static Scanner scan = new Scanner(System.in);


    public static void main(String [] args) throws FileNotFoundException {
        String option;
        do {
            menu();
            option = getOption();
            if (option.equalsIgnoreCase("AA")) {
                System.out.print("Activity name ? ");
                String activtyName = scan.nextLine();
                gymBase.addActivity(activtyName);
            }
            else if (option.equalsIgnoreCase("AM")) {
                System.out.print("Member's first name ? ");
                String firstName = scan.nextLine();
                System.out.print("Member's last name ? ");
                String lastName = scan.nextLine();
                gymBase.addMember(firstName, lastName);
            }
            else if (option.equalsIgnoreCase("LA")) {
                int nbrActivities = gymBase.getNbrActivities();
                for (int i=0; i<nbrActivities; i++) {
                    String activityName = gymBase.getActivity(i);
                    System.out.println(activityName);
                }
            }
            else if (option.equalsIgnoreCase("LM")) {
                int nbrMembers = gymBase.getNbrMembers();
                for (int i=0; i<nbrMembers; i++) {
                    String member = gymBase.getMember(i);
                    System.out.println(member);
                }
            }
            else if (option.equalsIgnoreCase("EM")) {
                System.out.print("Activity name ? ");
                String activity = scan.nextLine();
                System.out.print("Member's first name ? ");
                String firstName = scan.nextLine();
                System.out.print("Member's last name ? ");
                String lastName = scan.nextLine();
                if (!gymBase.addMemberToActivity(activity, firstName, lastName)) {
                    System.out.println("Unable to add member to activity.");
                    System.out.print("Check that both activity and member have");
                    System.out.println(" been added to database");
                }
            }
            else if (option.equalsIgnoreCase("LMA")){
                System.out.print("Activity name ? ");
                String activity = scan.nextLine();
                int nbrMembers = gymBase.getNbrMembersForActivity(activity);
                for (int i=0; i<nbrMembers; i++) {
                    System.out.println(gymBase.getMemberForActivity(activity, i));
                }
            }
            else if (option.equalsIgnoreCase("LAM")){
                System.out.print("Member's first name ? ");
                String firstName = scan.nextLine();
                System.out.print("Member's last name ? ");
                String lastName = scan.nextLine();
                int nbrActivities = gymBase.getNbrActivitiesForMember(firstName,lastName);
                for (int i=0; i<nbrActivities; i++) {
                    String activity=gymBase.getActivityForMember(firstName,lastName,i);
                    System.out.println(activity);
                }
            }
            else if (option.equalsIgnoreCase("S")) {
                System.out.println("File name ? ");
                String fileName = scan.nextLine();
                gymBase.save(fileName);
            }
            else if (option.equalsIgnoreCase("L")) {
                System.out.println("File name ? ");
                String fileName = scan.nextLine();
                gymBase.load(fileName);
            }
        }
        while(!option.equalsIgnoreCase("Q"));
    }

    private static String getOption() {
        System.out.print("Your option ? ");
        return scan.nextLine();
    }

    private static void menu() {
        System.out.println("Options are ...");
        System.out.println("AA: add activity");
        System.out.println("AM: add member");
        System.out.println("EM: enrol member on activity");
        System.out.println("LA: list activities");
        System.out.println("LM: list members");
        System.out.println("LMA: list members enrolled on activity");
        System.out.println("LAM: list activities to which member has enrolled");
        System.out.println("S: save to file");
        System.out.println("L: load from file");
        System.out.println("Q: quit program");
    }
}



There is one more module the GUI, but there is no need to post it as it is simply a simple interface off 'addactivity' 'addmember' etc.

The bit which you quoted not working is one bit I'm referring to, so for example the code I was using on the console to add activity wouldn't register what was typed in. Sorry for posting all the code but I hope this would give you a better idea of what i'm trying to achieve....which is to fully understand how one or two of these methods codes are written in order to accomplish the task described in the comment indent above each method.

JAVA is brand new to me and I feel i just need a well described example using the classes' I am using to then complete all the methods required in GymBase.java

Hope this explains it better, thanks for the help.

Chris

View Postkarabasf, on 06 April 2012 - 05:25 AM, said:

Ok, let's go this step by step. Your activity class is looking how it should look, so that's not a real problem. Now lets consider your addActvitiy:

   /**
     * Add an activity to the database.
     * @param activity The name of the activity to add.
     */[/color] //<---- Why is this here?
    public void addActivity(String activity) {
      Activity act = new Activity("activity");
    }



As you can see, the addActivity is flawed in two manners, namely:
- First, you do not use the String activity to instantiate an activity. Each time you call on addActivity("mystring") (for example) an object with the string value "activity" is created
- Second, the method itself does not add the activity to a datastructure. What kind of data structure are you using to store items? You're just stating Activity act = new Activity("activity") without doing anything with it. For example, you don't add it in some kind of database or datastructure.

So, think of what kind of datastructure you have or would use to store activities in the gymbase. Next change your code:

   /**
     * Add an activity to the database.
     * @param activity The name of the activity to add.
     */
    public void addActivity(String activity) {
      Activity act = new Activity(activity); //I removed the parenthesis (") as I do not want to instantiate an activity object with the value "activity" but with a value given by the argument of the method (which is activity)
     
     //Add the activity to the datastructure
     activities.add(act); //The exact code depends on the datastructure you'll use
    }



Next, the getActivity method. So you want to get the activity name at the i'th entry of the database (or datastructure in this context)
Now think of few things before you proceed:

- What should happen if i is negative, or better said:
- What should happen if i is outside the bounds of the datastructure (suppose I have n items and i = n + 1 for example)

You need to (though, it is not mandatory, but highly advisable) check the validity of i. Then, in pseudocode:

public String getActivity(int i){
  //Do check and return what ever you like if i fails the test You could also throw an exception for example  

 //Get the activity item at position i of your datastructure
 Activity temp = activities.get(i); //Actual code depends on your datastructure
 
  //Return the name of the activity
  return temp.getName();
}



Although, I have to admit, that this is just guessing. As I do not know what your interface IGymBase is, I cannot post an adequate solution for your problem.

Good luck! ^^


Thanks for a very quick and in depth response! I've just posted all the coding for each .java file which should show you more of what i'm trying to achieve. As regards to a data structure, if we assume there will be no more than 100 activities and 100 members, do you think an array should be sufficient?

Thanks
Was This Post Helpful? 0
  • +
  • -

#5 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 202
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 06 April 2012 - 06:04 AM

Ah, so as I expected, you didn't have a datastructure (yet) to hold the (planned?) activity objects.

An array would suffice, but you need to keep track of how many items there are actually in the database. Suppose I have an array with the size 100 and I only added 50 items. It wouldn't make sense if I want to access item 51, right? So you need a counter of how many items are actually in your activity Array.

Another datastructure you could use is the ArrayList. This is basically the same as an array, but more versatile. An in-depth tutorial can be found here: http://www.dreaminco...-static-arrays/

But to keep a long story short, if you're using an ArrayList, you don't even have to worry about the amount of activities and members you have! Why? Because the ArrayList is basically a dynamic array, it scales itself when it cannot hold any more items. And regarding the performance (although I doubt you'll face them), it's almost the same as a normal array. (although it might happen that the ArrayList uses more memory when compared with a normal Array)

However, what you're actually going to use, that is up to you ;)

Also, I saw that one of the requirement was to add members to an activity. Although this is something for later (when you want to expand the functionality), you need to extend/change the activity class such that it will be able to hold members.

Good luck with the assignment! ^^

This post has been edited by karabasf: 06 April 2012 - 06:07 AM

Was This Post Helpful? 0
  • +
  • -

#6 menace12  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 06-April 12

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 06 April 2012 - 06:12 AM

View Postkarabasf, on 06 April 2012 - 06:04 AM, said:

Ah, so as I expected, you didn't have a datastructure (yet) to hold the (planned?) activity objects.

An array would suffice, but you need to keep track of how many items there are actually in the database. Suppose I have an array with the size 100 and I only added 50 items. It wouldn't make sense if I want to access item 51, right? So you need a counter of how many items are actually in your activity Array.

Another datastructure you could use is the ArrayList. This is basically the same as an array, but more versatile. An in-depth tutorial can be found here: http://www.dreaminco...-static-arrays/

But to keep a long story short, if you're using an ArrayList, you don't even have to worry about the amount of activities and members you have! Why? Because the ArrayList is basically a dynamic array, it scales itself when it cannot hold any more items. And regarding the performance (although I doubt you'll face them), it's almost the same as a normal array. (although it might happen that the ArrayList uses more memory when compared with a normal Array)

However, what you're actually going to use, that is up to you ;)

Also, I saw that one of the requirement was to add members to an activity. Although this is something for later (when you want to expand the functionality), you need to extend/change the activity class such that it will be able to hold members.

Good luck with the assignment! ^^



Thanks for the reponse....however...I think a datastructure has already been declared here in the main.java
private static GymBase gymBase = new GymBase();


is that right?

Thanks
Was This Post Helpful? 0
  • +
  • -

#7 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 202
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 06 April 2012 - 06:20 AM

No, that's incorrect.

private static Gymbase gymBase = new GymBase();



Is declaring a new GymBase object. Better said, this line of code instantiates a new GymBase object in order to store your (user)defined activity objects.
Thus, this line itself does not instantiate a datastructure, it just initializes an object called GymBase where you can store your Activity objects ;)

I admit this is kinda vague, so lets use an analogy instead.

Suppose I am a cardealer (I always explain objects with cars, just don't ask me why).

Then:
private static int ShowRoom myShowroom = new ShowRoom();



Translating this line in my cardealership, this would mean that I have a ShowRoom, nothing else, nothing less. But you know that if you want to be a successful cardealer, you should be able to store Objects (cars in this context). However, if I don't define a (data)structure in my Showroom, I can't store anything in my showroom ;)

I hope this makes it somewhat clear ^^ (I know it's still hard to understand, but this is the closest analogy I could think of)

This post has been edited by karabasf: 06 April 2012 - 06:29 AM

Was This Post Helpful? 0
  • +
  • -

#8 menace12  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 06-April 12

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 06 April 2012 - 12:28 PM

View Postkarabasf, on 06 April 2012 - 06:20 AM, said:

No, that's incorrect.

private static Gymbase gymBase = new GymBase();



Is declaring a new GymBase object. Better said, this line of code instantiates a new GymBase object in order to store your (user)defined activity objects.
Thus, this line itself does not instantiate a datastructure, it just initializes an object called GymBase where you can store your Activity objects ;)

I admit this is kinda vague, so lets use an analogy instead.

Suppose I am a cardealer (I always explain objects with cars, just don't ask me why).

Then:
private static int ShowRoom myShowroom = new ShowRoom();



Translating this line in my cardealership, this would mean that I have a ShowRoom, nothing else, nothing less. But you know that if you want to be a successful cardealer, you should be able to store Objects (cars in this context). However, if I don't define a (data)structure in my Showroom, I can't store anything in my showroom ;)

I hope this makes it somewhat clear ^^ (I know it's still hard to understand, but this is the closest analogy I could think of)


Thanks for taking the time to explain, I much appreciate it. I've been looking at this all day and haven't got anywhere unfortunately. I posted all the coding above in one of my posts, do you think you could take a moment to have a look? I basically need an example of how i can piece the program together as the end code is complete, my job is to integrate it together. I've created an array on the basis of what you've said but I just don't know if it's correct or not...or even in the right class. I feel as if I can get one example done, I can learn from it and know how the different java files relate to each other to complete the rest of the methods in the GymBase.java file.

Thanks again
Was This Post Helpful? 0
  • +
  • -

#9 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 202
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 06 April 2012 - 12:58 PM

No problem, glad I could help ^^

The most important things are, that you'd only need to change two classes. The first reason being that you don't need to change the main, gui as these are complete already (at least, they look complete for me). Second, you said yourself that these classes shouldn't be changed. So we can conclude: leave these two for what it is.

Now, what I need to change is the:
- Activity class to hold members
- The GymBase class to hold activities and to assign members to activities

As this site is not a whole coding policy, I cannot (and won't be able) to give the full code. However, I can give you a small head start for the activity class. So try to follow the logic what I did and try to implement it.

Lets start. For the scope of my explanation I use an ArrayList.

public class Activity{
  ArrayList<Members> signedMembers; //Arraylist to assign members to the activity
  String activityName; //String to hold the name of the Activity

  //Default constructor
  //This instantiates an activity and an empty list. The reason why I want this to be empty is that I want to add members in a later stage
  public Activity(String activityName){
     this.activityName = activityName; //Assign the activity object with a name
     signedMembers = new ArrayList<Members>(); //ArrayList to hold the members

  //Your get name method here
  
  //Method to add a member. Note that I will perform a check to be sure that the member is not already in the activity
 public boolean addMember(Member signMember){
    if member is already assigned
        return false;
   
    //Else add the member to the activity
    signedMembers.add(signMember);
    return true;
   }
}



So this is our activity class, demonstrating some of the concepts of the arrayList.

Now, considering the GymBase and requirements:
- You need to be able to store members
- You need to be able to store activities

Thus, this means that you'd need not one, but two arraylists, which have to be instantiated when the GymBase is initialized (see the constructor for the activity for example)

Also, don't forget to perform checks. For example, I can't have two of the same members (unless if they exactly have the same name, but I guess you don't want to consider this situation at this moment)

So to give a basic outline:

public GymBase
  ArrayList members
  ArrayList activities
  
  //Constructor
  public Gymbase()
   //Initialize the empty arraylists members and activities
  
  public addActivity(String name)
     //Construct a new activity object tmp
     //Add the activity tmp to the arraylist activities

  public addMember
    //see addactivity

  //and so on...



There are a dozen of ways how to solve this. TO be honest, I would also add a field to the Members class to indicate whether the Member is already assigned to an activity.

Again, as it is not the policy of the board to give full code, I cannot help you further than this. However, I am quite certain that you will manage your way through. And of course, if you have further questions, add your (adjusted) code and we'll try to help.

The last piece of advice I can give you now is to step back (and stop bashing the keyboard) and to think of:
- What operations do I need?
- What should those operations do?
- How should those operations do it?

Where the last step also involves implementing it in Java.

Good luck! ^^

This post has been edited by karabasf: 06 April 2012 - 12:59 PM

Was This Post Helpful? 1
  • +
  • -

#10 menace12  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 06-April 12

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 07 April 2012 - 09:59 AM

View Postkarabasf, on 06 April 2012 - 12:58 PM, said:

No problem, glad I could help ^^

The most important things are, that you'd only need to change two classes. The first reason being that you don't need to change the main, gui as these are complete already (at least, they look complete for me). Second, you said yourself that these classes shouldn't be changed. So we can conclude: leave these two for what it is.

Now, what I need to change is the:
- Activity class to hold members
- The GymBase class to hold activities and to assign members to activities

As this site is not a whole coding policy, I cannot (and won't be able) to give the full code. However, I can give you a small head start for the activity class. So try to follow the logic what I did and try to implement it.

Lets start. For the scope of my explanation I use an ArrayList.

public class Activity{
  ArrayList<Members> signedMembers; //Arraylist to assign members to the activity
  String activityName; //String to hold the name of the Activity

  //Default constructor
  //This instantiates an activity and an empty list. The reason why I want this to be empty is that I want to add members in a later stage
  public Activity(String activityName){
     this.activityName = activityName; //Assign the activity object with a name
     signedMembers = new ArrayList<Members>(); //ArrayList to hold the members

  //Your get name method here
  
  //Method to add a member. Note that I will perform a check to be sure that the member is not already in the activity
 public boolean addMember(Member signMember){
    if member is already assigned
        return false;
   
    //Else add the member to the activity
    signedMembers.add(signMember);
    return true;
   }
}



So this is our activity class, demonstrating some of the concepts of the arrayList.

Now, considering the GymBase and requirements:
- You need to be able to store members
- You need to be able to store activities

Thus, this means that you'd need not one, but two arraylists, which have to be instantiated when the GymBase is initialized (see the constructor for the activity for example)

Also, don't forget to perform checks. For example, I can't have two of the same members (unless if they exactly have the same name, but I guess you don't want to consider this situation at this moment)

So to give a basic outline:

public GymBase
  ArrayList members
  ArrayList activities
  
  //Constructor
  public Gymbase()
   //Initialize the empty arraylists members and activities
  
  public addActivity(String name)
     //Construct a new activity object tmp
     //Add the activity tmp to the arraylist activities

  public addMember
    //see addactivity

  //and so on...



There are a dozen of ways how to solve this. TO be honest, I would also add a field to the Members class to indicate whether the Member is already assigned to an activity.

Again, as it is not the policy of the board to give full code, I cannot help you further than this. However, I am quite certain that you will manage your way through. And of course, if you have further questions, add your (adjusted) code and we'll try to help.

The last piece of advice I can give you now is to step back (and stop bashing the keyboard) and to think of:
- What operations do I need?
- What should those operations do?
- How should those operations do it?

Where the last step also involves implementing it in Java.

Good luck! ^^



Thanks very much! I've managed with your help to get activities and members entered and stored. I now need to add a member to an activity, would this involve creating a separate array? Surely it would require a 2D Array and not an Arraylist as it is storing 2 pieces of data i.e activity and member. Like you assumed, i'm required to use a boolean method, which checks whether the activity and member exist first of all, return true if correct, and of course return false if not true.

Are there any tips or examples of how to relate two array lists together in such a way?(I'm presuming this is my task).

Thanks for your help so far.

Kind Regards
Was This Post Helpful? 0
  • +
  • -

#11 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 202
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 07 April 2012 - 10:11 AM

Ah, it's good to hear that you advanced to a new level, as I'd say.
So what you now need to do is add a member to an activity right? One of the possibilities I'd consider, is using an arraylist in the activity object to keep track which members are enlisted for that activity.

In that case, I think it will look like this. (Assuming, you already have a boolean in the Members class)

public addMemberToActivity(String memberName, string activityName)
	 Member tempMember = null;
	 Activity tempActivity = null;

	//Check if the Member is in the memberList
	for each member mr in memberList
		if(memberName is equal to mr.Name)
			tempMember  = mr
			break; //you don't need to look further
	  
	//Check if member is not null
	if tempMember == null
		return false; //No need to continue as the member does not exist
	else if tempMember.IsAssigned  //Determine if the member is assigned
		return false; //No need to continue as the member is already assigned
	  
	//Check if the activity exist
    for each Activity act in memberList
		if(activityName is equal to act.Name)
			tempActivity  = act
			break; //you don't need to look further


	//Check if member is not null
	if tempActivity == null
		return false; //No need to continue as the specified activity does not exist

	//Add the member to an activity
	tempActivity.add(tempMember)
	  
	 //Set the status of the member to assigned
	 tempMember.setAssigned(true);
         return true;
}



Of course, you can play around with error messages (for example when the member does not exist)

The main problem is... The setup to be honest. You can go two ways (which is kind a annoying)

Either:
- You can assign an activity to the member. In this case your member should have a variable to hold the activity.
Drawbacks: you have to loop through each member and keep track of who gets assigned to what in order to determine how many members are enrolled for one activity
Advantage: You can determine directly in what activity a member is enrolled in

- My approach, you'd add a member to the activity. In this case your activity needs to have a variable ArrayList to hold each member assigned to the activity
Drawbacks: you cannot determine to which activity a member is assigned with. You will have to loop through the activity list, then loop through the arraylist of activity to determine who gets assigned where
Advantage: You can determine which members are assigned to an activity

- (best option) A combination of both. You assign a member to an activity and an activity to a member. This means that the member needs to be adjusted for this purpose. (so as the activity)

This would look like:
public addMemberToActivity(String memberName, string activityName)
	 Member tempMember = null;
	 Activity tempActivity = null;

	//Check if the Member is in the memberList
	for each member mr in memberList
		if(memberName is equal to mr.Name)
			tempMember  = mr
			break; //you don't need to look further
	  
	//Check if member is not null
	if tempMember == null
		return false; //No need to continue as the member does not exist
	else if tempMember.GetActivity != null  //Determine if the member is assigned by checking if it has an activity
		return false; //No need to continue as the member is already assigned
	  
	//Check if the activity exist
    for each Activity act in memberList
		if(activityName is equal to act.Name)
			tempActivity  = act
			break; //you don't need to look further


	//Check if Activity is not null
	if tempActivity == null
		return false; //No need to continue as the specified activity does not exist

	//Add the member to an activity
	tempActivity.add(tempMember)
	  
	 //Set the Activity ot the member
	 tempMember.seActivity(tempActivity);
         return true;
}



It really is up to you how you want to implement this. As I cannot determine what you exactly want, I just wait and nudge you a bit with this idea.

Good luck ^^

This post has been edited by karabasf: 07 April 2012 - 10:53 AM

Was This Post Helpful? 0
  • +
  • -

#12 menace12  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 06-April 12

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 08 April 2012 - 10:58 AM

View Postkarabasf, on 07 April 2012 - 10:11 AM, said:

Ah, it's good to hear that you advanced to a new level, as I'd say.
So what you now need to do is add a member to an activity right? One of the possibilities I'd consider, is using an arraylist in the activity object to keep track which members are enlisted for that activity.

In that case, I think it will look like this. (Assuming, you already have a boolean in the Members class)

public addMemberToActivity(String memberName, string activityName)
	 Member tempMember = null;
	 Activity tempActivity = null;

	//Check if the Member is in the memberList
	for each member mr in memberList
		if(memberName is equal to mr.Name)
			tempMember  = mr
			break; //you don't need to look further
	  
	//Check if member is not null
	if tempMember == null
		return false; //No need to continue as the member does not exist
	else if tempMember.IsAssigned  //Determine if the member is assigned
		return false; //No need to continue as the member is already assigned
	  
	//Check if the activity exist
    for each Activity act in memberList
		if(activityName is equal to act.Name)
			tempActivity  = act
			break; //you don't need to look further


	//Check if member is not null
	if tempActivity == null
		return false; //No need to continue as the specified activity does not exist

	//Add the member to an activity
	tempActivity.add(tempMember)
	  
	 //Set the status of the member to assigned
	 tempMember.setAssigned(true);
         return true;
}



Of course, you can play around with error messages (for example when the member does not exist)

The main problem is... The setup to be honest. You can go two ways (which is kind a annoying)

Either:
- You can assign an activity to the member. In this case your member should have a variable to hold the activity.
Drawbacks: you have to loop through each member and keep track of who gets assigned to what in order to determine how many members are enrolled for one activity
Advantage: You can determine directly in what activity a member is enrolled in

- My approach, you'd add a member to the activity. In this case your activity needs to have a variable ArrayList to hold each member assigned to the activity
Drawbacks: you cannot determine to which activity a member is assigned with. You will have to loop through the activity list, then loop through the arraylist of activity to determine who gets assigned where
Advantage: You can determine which members are assigned to an activity

- (best option) A combination of both. You assign a member to an activity and an activity to a member. This means that the member needs to be adjusted for this purpose. (so as the activity)

This would look like:
public addMemberToActivity(String memberName, string activityName)
	 Member tempMember = null;
	 Activity tempActivity = null;

	//Check if the Member is in the memberList
	for each member mr in memberList
		if(memberName is equal to mr.Name)
			tempMember  = mr
			break; //you don't need to look further
	  
	//Check if member is not null
	if tempMember == null
		return false; //No need to continue as the member does not exist
	else if tempMember.GetActivity != null  //Determine if the member is assigned by checking if it has an activity
		return false; //No need to continue as the member is already assigned
	  
	//Check if the activity exist
    for each Activity act in memberList
		if(activityName is equal to act.Name)
			tempActivity  = act
			break; //you don't need to look further


	//Check if Activity is not null
	if tempActivity == null
		return false; //No need to continue as the specified activity does not exist

	//Add the member to an activity
	tempActivity.add(tempMember)
	  
	 //Set the Activity ot the member
	 tempMember.seActivity(tempActivity);
         return true;
}



It really is up to you how you want to implement this. As I cannot determine what you exactly want, I just wait and nudge you a bit with this idea.

Good luck ^^


Thanks again for taking the time to help, it's much appreciated. I've been looking over this part of the coursework for a while now trying to get my head around certain aspects. There are a few things I don't understand, and this I feel is a lack of attention to detail in the way certain things have been taught...with other fellow students struggling too recently. I've only been looking at Java since the start of February.... so please excuse my beginner approach to things!

I just wanted to ask a few questions if possible...

1. Firstly what exactly is the purpose of the tempMember variables?
2. What does mr stand for in this method example?
3. The tempMember.setAssigned.....is that referring back to the signed members in the activity class?
4. Finally i created two arraylists for activities and members in the form of - ArrayList Activities = new ArrayList(100)
....however this arraylist contained within the activity class....ArrayList<Members> signedMembers...is defined differently and I can't understand the difference between the two, and more importantly why it's defined in such a manner? Can you explain this possibly?

Apologies again for asking what may seem simple questions. I do feel alot of content has been skipped in the teaching process...however on the plus side it has increased my interest in the language and to learn more without a doubt.

This third part is in for tomorrow so I'm hoping to get to grips by the end of tonight of what exactly i should be writing.

Thanks again.
Was This Post Helpful? 0
  • +
  • -

#13 karabasf  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 202
  • View blog
  • Posts: 417
  • Joined: 29-August 10

Re: Add, Get number, return methods from class - Beginner at Java...

Posted 08 April 2012 - 11:47 AM

Sure, no problem to ask questions. We all have to start somewhere anyways. So lets go through your questions:

1) the temporary variables are used to compare them or to extract data from it. This is because when you loop (as in the for each part), the variables only exist inside the loop. And we need them outside the loop to compare them.

So, a small lesson about scope:

for (int i = 0; i < 5; i++){
   int x += i;
}

System.out.println(x); //Will give an error



This will give an error as x is not defined outside the loop. For Java x simply does not exist (defined might be a better word) outside the for loop. This on the other hand, is valid:

int x = 0;
for (int i = 0; i < 5; i++){
   x += i;
}

System.out.println(x); //is ok



Why? Well, now x does not only exist in the loop, but also outside. This same effect is what I am trying to achieve with the temporary variables.

2) mr stands for a member object in the memberlist (see it as a temporary variable inside the loop). If you look closely at the for each loop, I basically say (lets put this in the linguistic side):

for each Member in Memberlist do{
  If the Name of the Member is the same as User given Name
      Assign Member to tempMember
      break; //stop loop
}



I hope this makes it clear.


3) tempMember.setAssigned() is meant to set the status of the tempmember. If you assign it to an activity (assuming it passed the tests) , it's status needs to change into "Assigned" (Which is a boolean true or false)

4) This has to do with the definition. I am assuming that you are implementing option 3 of my last post.

If that's the case, you need to have a field (a variable and not an arraylist) in the memberclass, while having a ArrayList<Member> in the Activity class.

This way you can add an activity to the member, and an Member to the activity. Or is this not the answer you are searching for?

If so, I'll elaborate it further.

In your GymBase class, you have 2 arraylists, one containing the (possible) activities, while the other contains the members of the gym.

Suppose I have this situation: I want to pick an Activity and see which of the members are enrolled in that. I can do it the hard way, or the easy way. If I already have an arraylist in the activity class, containing the members, I can call upon a method like act.getSignedMembers() (or something like that) which returns an ArrayList of Members which are assigned to that single activity.

As you can see, there is a difference. While the ArrayList<Members> in your GymBase contains the members of the GymBase, the ArrayList<Members> in the activity contains the members which are enrolled in that Activity.

And don't worry about simple questions. As I'd said, you need to start of somewhere. But I have to admit, this is quite a good assignments as it covers quite a lot of aspects in designing a (nice) piece of software.

Anyways, good luck ^^

Edit:
Also, I hope you created Arraylist in this trend:

ArrayList<Activity> activityList = new ArrayList<Activity>(); 



If you do:
ArrayList<Activity> activityList = new ArrayList(); 



I am not sure if this would be type safe...

This post has been edited by karabasf: 08 April 2012 - 12:01 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1