stringValue
有没有办法可以在java中创建一个计数器来计算分配给MembershipStat.RegMember和MembershipStat.CoPresident等的人数?基本上是告诉我有多少注册人等的方式
答案 0 :(得分:1)
我认为没有包装右侧(或类似的)
的方法ChaseW = add(MembershipStat.CoPresident);
其中add类似于
static int[] counters = new int[MembershipStat.values().length];
static MembershipStat add(MembershipStat stat) {
counters[stat.ordinal]++;
return stat;
}
如有必要,请删除
static MembershipStat remove(MembershipStat stat){
counters[stat.ordinal]--;
return stat;
}
答案 1 :(得分:0)
我建议添加一个Member
类来为您捕获此信息:
class Member {
private static final EnumMap<MembershipStat, Integer> statusCount = new EnumMap<>(MembershipStat.class);
private MembershipStat status;
private String name;
public Member(String name, MembershipStat status) {
this.status = status;
this.name = name;
statusCount.put(status, getStatCount(status) + 1);
}
public static int getStatCount(MembershipStat status) {
return statusCount.getOrDefault(status, 0);
}
}
然后您可以将成员添加为:
Member mrLee = new Member("Peter Lee", MembershipStat.Secretary);
获取特定状态的计数:
Member.getCount(MembershipStat.Treasurer);
理想情况下,您还可以处理成员的状态更改:
public void changeStatus(MembershipStat status) {
assert getStatCount(this.status) >= 1;
statusCount.put(this.status, getStatCount(this.status) - 1);
this.status = status;
statusCount.put(this.status, getStatCount(this.status) + 1);
}
答案 2 :(得分:-1)
根据您的所有需求进行调整。
public int checkFor(MembershipStat[] ms, MembershipStat check){
int x = 0;
for(MembershipStat m : ms){
if(m.equals(check))x++;
}
return x;
}
我不确定你是如何设置名单的,使用Map / HashMap设置可能是有益的。 对于你的例子,它看起来有点像这样:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Test1 {
enum MembershipStat {CoPresident, Secretary, Treasurer, RegMember,Sponser}
public static void main (String[] args)
{
final int CoPresidents = 2;
Map<String, MembershipStat> roster = new HashMap<String, MembershipStat>();
roster.put("ChaseW", MembershipStat.CoPresident);
roster.put("Saif", MembershipStat.CoPresident);
roster.put("MrLee", MembershipStat.Sponser);
roster.put("Rahil", MembershipStat.Secretary);
roster.put("Donovon", MembershipStat.RegMember);
roster.put("Armaan", MembershipStat.RegMember);
roster.put("Elliot", MembershipStat.RegMember);
roster.put("JacksonM", MembershipStat.Treasurer);
roster.put("Cyrus", MembershipStat.RegMember);
roster.put("Avery", MembershipStat.RegMember);
roster.put("PeterM", MembershipStat.RegMember);
roster.put("Mahdi", MembershipStat.RegMember);
roster.put("GeorgeW", MembershipStat.RegMember);
System.out.println(checkFor(roster, MembershipStat.RegMember));
}
public static int checkFor(Map<String, MembershipStat> roster, MembershipStat check){
int x = 0;
Iterator<MembershipStat> it = roster.values().iterator();
while(it.hasNext()){
MembershipStat y = it.next();
System.out.println(y);
if(y.equals(check))
x++;
}
return x;
}
}
随意使用并询问问题! :d