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

Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last
• 07-01-2011, 07:37 PM
ralf
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);

int sum = 0;
Iterator i = nmonth.iterator();
while(i.hasNext()) {
sum += count;
// System.out.println(sum);
return sum;
• 07-01-2011, 07:41 PM
Sort it (see the Collections class) then iterate through it counting the length of the sequences.
• 07-01-2011, 07:56 PM
Norm
Quote:

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.
• 07-01-2011, 10:15 PM
ralf
Quote:

Originally Posted by Norm
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?
• 07-01-2011, 10:20 PM
Norm
Where do you keep the counts for each month?
Quote:

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.
• 07-01-2011, 10:21 PM
ralf
Quote:

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?
• 07-01-2011, 10:25 PM
Norm
What is stored in both of the ArrayLists?
Do you have a class (Membership) that has the month and the count for that month?
• 07-01-2011, 10:32 PM
ralf
Quote:

Originally Posted by Norm
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.

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?
• 07-01-2011, 10:36 PM
ralf
Quote:

Originally Posted by Norm
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.

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?
• 07-01-2011, 10:38 PM
Norm
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.
• 07-01-2011, 11:01 PM
ralf
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.");     } }```
• 07-01-2011, 11:03 PM
ralf
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.");     } }```
• 07-01-2011, 11:16 PM
Norm
Where is the test script for it? It needs a main() method that does something to demonstrate the problem.
• 07-01-2011, 11:20 PM
ralf
I am doing it in BlueJ. So there are many things that actually happen behind the scene
• 07-01-2011, 11:28 PM
Norm
Quote:

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.
• 07-01-2011, 11:38 PM
Norm
Check this line. There is something wrong here.
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.
• 07-02-2011, 12:00 AM
ralf
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?```
• 07-02-2011, 12:06 AM
Norm
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
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++;
• 07-02-2011, 12:35 AM
ralf
As you understand I am a newbie. Where do I need to place the count++?
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;```
• 07-02-2011, 12:40 AM
Norm
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.
Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last