简体   繁体   English

如何计算 java 中 arraylist 中相同数字的出现次数?

[英]How to count occurence of the same number in an arraylist in java?

I have an arraylist in java where the content is added from input of the user.我在 java 中有一个 arraylist,其中内容是从用户的输入中添加的。 The user add name, number for the month and a number for the year.用户添加姓名、月份编号和年份编号。 Like this: Name: Bob, month: 4, year: 11像这样:姓名:Bob,月份:4,年份:11

My task is to find how many user have added the same month number to the arraylist.我的任务是找出有多少用户在 arraylist 中添加了相同的月份编号。 Count the occurence of the same month number and print it out.统计同月数的出现次数并打印出来。

I know I must iterate over the arraylist and to store the occurence somwhere until the iterator have finished to search trough the collection of the arraylist and then print out how many times the same month number has been added.我知道我必须遍历 arraylist 并将发生的地方存储在某个地方,直到迭代器完成搜索 arraylist 的集合,然后打印出添加了多少次相同的月份数。

I am quiet stuck on this task.我很安静地坚持这项任务。 Even tough it is an easy task.即使是艰巨的任务,也是一件容易的事。

Thank for your help!感谢您的帮助!

I have three classes我有三个班

public class Person
{
    // The name of this user.
    private final String name;

    /**
     * Create a new user with the given name.
     * @param name The user's name.
     */
    public Person(String name)
    {
        this.name = name;
    }

    /**
     * @return The user's name.
     */
    public String getName()
    {
        return name;
    }
}

///////////////////////////////// ////////////////////////////

/**
 * 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;
    }
}

//////////////////////////////////////////// ////////////////////////////////////

    import java.util.ArrayList;
    import java.util.Iterator;
    /**
     * Store details of club memberships.
     * 
     */
    public class Club
    {
        // Define any necessary fields here ...
        private ArrayList club;
       // private String member = club;
        private int joined; 
        /**
         * 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);


        }

//////////////////////////////////////////////////////////    
//    public int getJoined()
//    {
//        return joined;
//    }
//////////////////////////////////////////////////////////    
    /**
     * @return The number of members (Membership objects) in
     * the club.
     */
     public int numberOfMembers()
    {
       return club.size();
    }
///////////////////////////////////////////////////////////////////////////////////    
    public int joinedInMonth(int month)
    {
         //int joined = month;
        if(month < 1 || month > 12)
        {
            System.out.println("Not a valid month");

        }


      else{

//     int countMonth(ArrayList<Person> person, int month)
  {
      int count = 0;
        for (Club club : people)
         if (person.getMonth() == month) count++;
           return count;
} 

        }
        // using traditional for loop
       //  int joined = month;
       // for(int i = 0; i < club.size(); i++)
        //                      {

        //   System.out.println(i+1 + ": " + club.get(i));
         //  }       
//              

//               for(Iterator i = club.iterator();i.hasNext();)
//                  {
//                     
//                    System.out.println(i.next());
//   
//
//          }
         return 0;   
      }

    }

///////////////////////////////////////// //////////////////////////////////

This is what I have so far with the method to count occurence of the same number in the arraylist:这就是我迄今为止使用的方法来计算 arraylist 中相同数字的出现:

 public int joinedInMonth(int month)
    {
        int joined = month;
        if(joined < 1 || joined > 12){
            System.out.println("Not a valid month");
            }
      else{   
           int count = 0;
          Iterator it = club.iterator();
               while(it.hasNext()) {
          Membership membership = (Membership) it.next();
           if(joined == membership.getMonth());count++;


               System.out.println("Month " + membership.getMonth());
                    return count;

but I cant understand how I can store the value from count into a new arraylist?但我不明白如何将计数中的值存储到新的 arraylist 中? Any help?有什么帮助吗?

Since you haven't posted for 2 hours, here's one way:由于您已经有 2 小时没有发帖了,这里有一种方法:

class Person {
    String name;
    int month;
    int year;
    // with getters()
}

int countMonth(List<Person> people, int month) {
    int count = 0;
    for (Person person : people)
        if (person.getMonth() == month) count++;
    return count;
}

For this kind of task a would use a Hashtable<Integer, List<Person>> where all person of a particular month would be index toghether in one List.对于这种任务,a 将使用Hashtable<Integer, List<Person>> ,其中特定月份的所有人员都将被索引到一个 List 中。

Hashtable<Integer, List<Person>> index = new Hashtable<Integer, List<Person>>();
for (Person person : persons) {
    if (index.get(person.month) == null) {
        index.put(person.month, new ArrayList<Person>());
    }
    index.get(person.month).add(person);
}

The you can retrive a list of person according to their month.您可以根据他们的月份检索人员列表。 This code will only print the month and the number of persons contained in list.此代码将仅打印列表中包含的月份和人数。

for (int i = 1; i <= 12; i++) {
    int count = 0;
    if (index.get(i) != null) {
        count = index.get(i).size();
    }
    System.out.println("%d: %d", i, count);
}

Hashtables are really nice for this kind of tasks were you have to regroup elements toghether or access an value using a key (here its the month as an Integer and the value is List<Person> ).如果您必须将元素重新组合在一起或使用键访问值(这里的月份为Integer并且值为List<Person> ),哈希表非常适合此类任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM