Page 1 of 2 12 LastLast
Results 1 to 20 of 38
  1. #1
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default How to count occurence of the same number in an arraylist

    Hello to you all!
    I have a method where I can insert a number for a month and then find how many have joined in a Club in that month. Belove you can see the code for it.
    My problem is to add the month numbers from arraylist1 to arraylist2 and then sum it up and print out the number of people who joined in that particular month.
    I hope you can help me with this? I am just traying to refresh some very basic understanding of java.
    public int joinedInMonth(int month)
    {
    int joined = month;
    if(joined < 1 || joined > 12){
    System.out.println("Not a valid month");
    }
    else{
    int count = 0;
    //int countMount
    ArrayList nmonth = new ArrayList();
    Iterator it = club.iterator();
    while(it.hasNext()) {
    Membership membership = (Membership) it.next();
    if(joined == membership.getMonth())count++;{
    //System.out.println(count);
    nmonth.add(count);

    int sum = 0;
    Iterator i = nmonth.iterator();
    while(i.hasNext()) {
    sum += count;
    // System.out.println(sum);
    return sum;

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Sort it (see the Collections class) then iterate through it counting the length of the sequences.

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    My problem is to add the month numbers from arraylist1 to arraylist2
    I don't understand what you are doing here.
    Does array1 have a value in each element and you want to add those elements one by one to the corresponding elements in array2? I assume the two arrays are the same size. Then use a normal for loop (not iterator) thru all the elements and add those from a1 to a2. See the ArrayList class for methods to get and set values of its elements.

  4. #4
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    I don't understand what you are doing here.
    Does array1 have a value in each element and you want to add those elements one by one to the corresponding elements in array2? I assume the two arrays are the same size. Then use a normal for loop (not iterator) thru all the elements and add those from a1 to a2. See the ArrayList class for methods to get and set values of its elements.

    No, the arraylist1 does not necessarily have a value in each element. I just want to for instance insert number 4 for April month and then find out how many have joined in that month. If it is two person who joined the output should be 2 for that month.
    I wish only to search trough arraylist1 and add what I find to arraylist2, then count how many and print it out.
    Any idea?

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    Where do you keep the counts for each month?
    I just want to for instance insert number 4 for April month and then find out how many have joined in that month
    What is the 4 here? Does it represent the month of April?

    How are you going to use an ArrayList to hold the data if it does not have an element for each month? For example the first element is for January and the last element is for December and there are 10 elements between those two.

  6. #6
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Quote Originally Posted by masijade View Post
    Sort it (see the Collections class) then iterate through it counting the length of the sequences.
    Thank for the answer from you and norm.
    I have managed to iterate trough the collection in arraylist1,as for instance find the month, but I have no idea how I can add those result into arraylist2 and then count how many I found and then print it out.
    Any idea?

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    What is stored in both of the ArrayLists?
    Do you have a class (Membership) that has the month and the count for that month?

  8. #8
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Where do you keep the counts for each month?

    What is the 4 here? Does it represent the month of April?

    How are you going to use an ArrayList to hold the data if it does not have an element for each month? For example the first element is for January and the last element is for December and there are 10 elements between those two.
    Hello thank you for your answer!
    Yes 4 represent april. This is a task for a "Club" from a book. It has three classes. The Club has a join method where people are being added to the Club. There can have been many who have joined in month of January, February and maybe none have joined in Mars, in April there can have been some who have joined.
    And the method I am trying to do now there can I insert a number for a month, but I can't manage to add what I found into arraylist2, count and print it out.
    Any idea?

  9. #9
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Where do you keep the counts for each month?

    What is the 4 here? Does it represent the month of April?

    How are you going to use an ArrayList to hold the data if it does not have an element for each month? For example the first element is for January and the last element is for December and there are 10 elements between those two.
    Hello thank you for your answer!
    Yes 4 represent april. This is a task for a "Club" from a book. It has three classes. The Club has a join method where people are being added to the Club. There can have been many who have joined in month of January, February and maybe none have joined in Mars, in April there can have been some who have joined.
    And the method I am trying to do now there can I insert a number for a month, but I can't manage to add what I found into arraylist2, count and print it out.
    Any idea?

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    Can you post your current code showing where you are and what you problem is.
    Why do you have two lists with data?
    What is in list one and what is in list two?

    Please wrap your code in code tags to preserve formatting. Code tags are generated by the # icon above the input area.

  11. #11
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Java Code:
    ///////////////////////// Thank for your help!
    Class one Club
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    /**
     * Store details of club memberships.
     *
     */
    public class Club
    {
        // Define any necessary fields here ...
        private ArrayList club;
        private ArrayList nMonth;
        /**
         * Constructor for objects of class Club
         */
        public Club()
        {
            // Initialise any fields here ...
           club = new ArrayList();
            
        }
        
        /**
         * Add a new member to the club's list of members.
         * @param member The member object to be added.
         */
        public void join(Membership member)
        {
          club.add(member);
          //System.out.println(member);
          
    
        }
      
        /**
         * @return The number of members (Membership objects) in
         * the club.
         */
         public int numberOfMembers()
        {
           return club.size();
        }
        
        public int joinedInMonth(int month)      //This is the method where I can't undertand
        {
            int joined = month;
            if(joined < 1 || joined > 12){
                System.out.println("Not a valid month");
                }
          else{   
               int count = 0;
            //int countMount 
            ArrayList nmonth = new ArrayList();
            Iterator it = club.iterator();
            while(it.hasNext()) {
               Membership membership = (Membership) it.next(); //Here I iterate trough the list to find the month I wish to get result from
               if(joined == membership.getMonth())count++;{
                 //System.out.println(count);
                   nmonth.add(count); //Here I wish to add the result into arraylist2 with the name nmonth
    
                   int sum = 0;
                   Iterator i = nmonth.iterator();//Here I try to iterate trough the list and count how many there are, sum it up and return it
                    while(i.hasNext()) {
                          sum += count;
                                 // System.out.println(sum);
                                return sum;
         }
       }
             
     }
               }
        return 0;
    }
    } 
    ////////////////////////////////////////////////
    second class membership
    /**
     * Store details of a club membership.
     * 
     */
    public class Membership
    {
        // The name of the member.
        private String name;
        // The month in which the membership was taken out.
        private int month;
        // The year in which the membership was taken out.
        private int year;
    
        /**
         * Constructor for objects of class Membership.
         * @param name The name of the member.
         * @param month The month in which they joined. (1 ... 12)
         * @param year The year in which they joined.
         */
        public Membership(String name, int month, int year)
            throws IllegalArgumentException
        {
            if(month < 1 || month > 12) {
                throw new IllegalArgumentException(
                    "Month " + month + " out of range. Must be in the range 1 ... 12");
            }
            this.name = name;
            this.month = month;
            this.year = year;
        }
        
        /**
         * @return The member's name.
         */
        public String getName()
        {
            return name;
        }
        
        /**
         * @return The month in which the member joined.
         * A value in the range 1 ... 12
         */
        public int getMonth()
        {
            return month;
        }
    
        /**
         * @return The year in which the member joined.
         */
        public int getYear()
        {
            return year;
        }
    
        /**
         * @return A string representation of this membership.
         */
        public String toString()
        {
            return "Name: " + name +
                   " joined in month " +
                   month + " of year " + year;
        }
    }
    //////////////////////////////////////////
    Third class clubdemo
    /**
     * Provide a demonstration of the Club and Membership
     * classes.
     * 
     */
    public class ClubDemo
    {
        // instance variables - replace the example below with your own
        private Club club;
    
        /**
         * Constructor for objects of class ClubDemo
         */
        public ClubDemo()
        {
            club = new Club();
        }
    
        /**
         * Add some members to the club, and then
         * show how many there are.
         * Further example calls could be added if more functionality
         * is added to the Club class.
         */
         public void demo()
         {
             club.join(new Membership("David", 2, 2004));
    //         club.join(new Membership("Michael", 1, 2004));
    //         club.join(new Membership("Borat", 4, 2004));
    //         club.join(new Membership("Harry", 5, 2004));
             System.out.println("The club has " +
                                club.numberOfMembers() +
                                " members.");
         }
    }

  12. #12
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Java Code:
    ///////////////////////// Thank for your help!
    Class one Club
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    /**
     * Store details of club memberships.
     *
     */
    public class Club
    {
        // Define any necessary fields here ...
        private ArrayList club;
        private ArrayList nMonth;
        /**
         * Constructor for objects of class Club
         */
        public Club()
        {
            // Initialise any fields here ...
           club = new ArrayList();
            
        }
        
        /**
         * Add a new member to the club's list of members.
         * @param member The member object to be added.
         */
        public void join(Membership member)
        {
          club.add(member);
          //System.out.println(member);
          
    
        }
      
        /**
         * @return The number of members (Membership objects) in
         * the club.
         */
         public int numberOfMembers()
        {
           return club.size();
        }
        
        public int joinedInMonth(int month)      //This is the method where I can't undertand
        {
            int joined = month;
            if(joined < 1 || joined > 12){
                System.out.println("Not a valid month");
                }
          else{   
               int count = 0;
            //int countMount 
            ArrayList nmonth = new ArrayList();
            Iterator it = club.iterator();
            while(it.hasNext()) {
               Membership membership = (Membership) it.next(); //Here I iterate trough the list to find the month I wish to get result from
               if(joined == membership.getMonth())count++;{
                 //System.out.println(count);
                   nmonth.add(count); //Here I wish to add the result into arraylist2 with the name nmonth
    
                   int sum = 0;
                   Iterator i = nmonth.iterator();//Here I try to iterate trough the list and count how many there are, sum it up and return it
                    while(i.hasNext()) {
                          sum += count;
                                 // System.out.println(sum);
                                return sum;
         }
       }
             
     }
               }
        return 0;
    }
    } 
    ////////////////////////////////////////////////
    second class membership
    /**
     * Store details of a club membership.
     * 
     */
    public class Membership
    {
        // The name of the member.
        private String name;
        // The month in which the membership was taken out.
        private int month;
        // The year in which the membership was taken out.
        private int year;
    
        /**
         * Constructor for objects of class Membership.
         * @param name The name of the member.
         * @param month The month in which they joined. (1 ... 12)
         * @param year The year in which they joined.
         */
        public Membership(String name, int month, int year)
            throws IllegalArgumentException
        {
            if(month < 1 || month > 12) {
                throw new IllegalArgumentException(
                    "Month " + month + " out of range. Must be in the range 1 ... 12");
            }
            this.name = name;
            this.month = month;
            this.year = year;
        }
        
        /**
         * @return The member's name.
         */
        public String getName()
        {
            return name;
        }
        
        /**
         * @return The month in which the member joined.
         * A value in the range 1 ... 12
         */
        public int getMonth()
        {
            return month;
        }
    
        /**
         * @return The year in which the member joined.
         */
        public int getYear()
        {
            return year;
        }
    
        /**
         * @return A string representation of this membership.
         */
        public String toString()
        {
            return "Name: " + name +
                   " joined in month " +
                   month + " of year " + year;
        }
    }
    //////////////////////////////////////////
    Third class clubdemo
    /**
     * Provide a demonstration of the Club and Membership
     * classes.
     * 
     */
    public class ClubDemo
    {
        // instance variables - replace the example below with your own
        private Club club;
    
        /**
         * Constructor for objects of class ClubDemo
         */
        public ClubDemo()
        {
            club = new Club();
        }
    
        /**
         * Add some members to the club, and then
         * show how many there are.
         * Further example calls could be added if more functionality
         * is added to the Club class.
         */
         public void demo()
         {
             club.join(new Membership("David", 2, 2004));
    //         club.join(new Membership("Michael", 1, 2004));
    //         club.join(new Membership("Borat", 4, 2004));
    //         club.join(new Membership("Harry", 5, 2004));
             System.out.println("The club has " +
                                club.numberOfMembers() +
                                " members.");
         }
    }

  13. #13
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    Where is the test script for it? It needs a main() method that does something to demonstrate the problem.

  14. #14
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    I am doing it in BlueJ. So there are many things that actually happen behind the scene

  15. #15
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    things that actually happen behind the scene
    Then I can't compile and execute your code.
    You will need to create a program that can compile and execute if you want someone to help you debug it.

  16. #16
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    Check this line. There is something wrong here.
    Java Code:
               if(joined == membership.getMonth())count++;{
    Also the {}s underneath that line are not formatted correctly so it is hard to see the nesting of the logic.

  17. #17
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    Java Code:
     public int joinedInMonth(int month)
        {
            int joined = month;
            if(joined < 1 || joined > 12)
              {
                System.out.println("Not a valid month");
                }
          else
             {   
               int count = 0;
            ArrayList nmonth = new ArrayList();//create a new arraylist
            Iterator it = club.iterator();
            while(it.hasNext()) 
            {
               Membership membership = (Membership) it.next();
               
               if(joined == membership.getMonth())count++;// What is wrong with this one?
                 {    // have added{
                 //System.out.println(count);
                   nmonth.add(count);
                }//have added }
                   int sum = 0;
                   Iterator i = nmonth.iterator();
                    while(i.hasNext()) {
                          sum += count;
                                 // System.out.println(sum);
                                return sum;
         }
       }
                
     }
        return 0;        
    // can you tell me anything you might see of problems?

  18. #18
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    First thing I'd do is design what I wanted the method to do. Then I'd write some comments describing the steps I was going to take to do it. Then I'd write the code as per the comments that describe the steps to be taken.

    In your posted code: The }s are still messed up and not aligned with their opening {s

    What is this code supposed to do? Notice the hanging count++; statement
    Java Code:
               if(joined == membership.getMonth())[B]count++;[/B]// What is wrong with this one?
                 {    // have added{
    The { on the last line above is not part of the if statement because of the count++;

  19. #19
    ralf is offline Member
    Join Date
    Jul 2011
    Posts
    98
    Rep Power
    0

    Default

    As you understand I am a newbie. Where do I need to place the count++?
    Java Code:
       public int joinedInMonth(int month)
        {
            int joined = month;
            if(joined < 1 || joined > 12)
              {
                System.out.println("Not a valid month");
                }
          else
             {   
               int count = 0;
            //int countMount 
            ArrayList nmonth = new ArrayList();
            Iterator it = club.iterator();
            while(it.hasNext()) 
            {
               Membership membership = (Membership) it.next();
            
               if(joined == membership.getMonth())
                 {
                 count++;                                            //is it better here?
                 nmonth.add(count);
                }
                   int sum = 0;
                   Iterator i = nmonth.iterator();
                    while(i.hasNext()) 
                       {
                          sum += count;
                                 // System.out.println(sum);
                                return sum;
                        }
                    }
                
                }
                    return 0;

  20. #20
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    That method needs a new design.
    I assume that all it does is count the number of members that joined in a selected month and return that value.
    Is that correct?
    To do that you need to look at each member's join date and increment the count if it is for the selected month.
    Go through all the members, looking and incrementing as appropriate.
    At the end return the count.

Page 1 of 2 12 LastLast

Similar Threads

  1. how to count number of pages printed?
    By absmarty in forum New To Java
    Replies: 10
    Last Post: 01-31-2012, 06:20 PM
  2. How to count number of palindrome in a string??
    By i4ba1 in forum Advanced Java
    Replies: 5
    Last Post: 04-12-2011, 12:58 PM
  3. day number count
    By droidus in forum New To Java
    Replies: 14
    Last Post: 03-23-2011, 10:15 PM
  4. Array count number Occurances
    By gwithey in forum New To Java
    Replies: 2
    Last Post: 04-17-2009, 08:34 PM
  5. count occurence of word in a line of text
    By sinyi88 in forum New To Java
    Replies: 19
    Last Post: 02-28-2009, 07:37 AM

Tags for this Thread

Posting Permissions

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