将概率分配给随机枚举对象

时间:2013-02-24 03:42:31

标签: java string random enums arraylist

所以我在这里有一个枚举:

public enum Party {

    DEMOCRAT, INDEPENDENT, REPUBLICAN
}

我现在有三个班级之一:

public class ElectoralCollege {
    public static final String FILE = "Electoral201X.txt";
    private ArrayList <State> stateVotes;
    Random rand = new Random();

    public ElectoralCollege() throws IOException    {

        stateVotes = new ArrayList<State>();
        assignStates();
    }

    public void assignStates() throws IOException   {

        File f = new File(FILE);
        Scanner fReader = new Scanner(f);

        while(fReader.hasNext())    {

            String stateData = fReader.nextLine();
            int stateEnd = stateData.indexOf(" - ");
            String stateName = stateData.substring(0, stateEnd);
            String stateVotes = stateData.substring(stateEnd + 2);
            //System.out.println(stateName + " " + stateVotes);


        }

在这里,我正在阅读一个文件,其中包含州名和选举投票数,如下所示“佛罗里达 - 29”,所以这一切都已经找到了。

我接下来要做的是使用随机对象从我的Party枚举中为其分配一方。共和党和民主党必须有2/5的机会获胜......而独立必须有1/5的机会。然后我必须创建一个State对象(它将状态名称,投票数和派对作为参数)并将其抛入该arraylist中。最有可能为每个循环使用a,只需要对此进行更多的研究。

我的问题是如何使用这个随机对象rand以及这三方的设定概率,并执行它?有人有任何想法吗?

编辑:底线是:如何为这三个缔约方实施2/5和1/5概率,然后根据这些概率调用随机对象给我一个派对?

在mre的回答之后,我这样做了:

Random rand = new Random();
    List<Party> parties = Arrays.asList(Party.DEMOCRAT, Party.DEMOCRAT, Party.REPUBLICAN, Party.REPUBLICAN, Party.INDEPENDENT);

稍后......

public void assignStates()抛出IOException {

File f = new File(FILE);
Scanner fReader = new Scanner(f);

while(fReader.hasNext())    {

    String stateData = fReader.nextLine();
    int stateEnd = stateData.indexOf(" - ");
    String stateName = stateData.substring(0, stateEnd);
    String numVote = stateData.substring(stateEnd + 2);

    Party winner = parties.get(rand.nextInt(5));
    //System.out.println(stateName + " " + numVote + " " + winner);

    State voteInfo = new State(stateName, Integer.parseInt(numVote.trim()), winner);
    stateVotes.add(voteInfo);

}

}

已回答,新问题:Using a foreach loop to add values from an arraylist, and then print them using accessors

1 个答案:

答案 0 :(得分:1)

有5个Party个实例的集合,其中2个为DEMOCRAT,2个为REPUBLICAN,1个为INDEPENDENT,然后使用随机数生成器生成随机索引(即0-4)以访问例如

import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class Demo 
{
    public static void main(String[] args) 
    {
       Random r = new Random();
       List<Party> parties = Arrays.asList(Party.DEMOCRAT, Party.DEMOCRAT, Party.REPUBLICAN, Party.REPUBLICAN, Party.INDEPENDENT);

       System.out.println(parties.get(r.nextInt(parties.size())));
    }

    enum Party
    {
        DEMOCRAT,
        REPUBLICAN,
        INDEPENDENT;
    }
}