So I have an enum here:
public enum Party {
DEMOCRAT, INDEPENDENT, REPUBLICAN
}
and I currently have this, one of three classes:
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);
}
Here I am reading from a file that has state names and their number of electoral votes as follows "Florida - 29", so that's all figured out.
What I have to do next is use a random object to assign a party to them from my Party enum. Republican and Democrat must have a 2/5 chance of winning...while Independent must have a 1/5 chance. Then I must create a State object (which takes the state name, number of votes, and the party in as parameters) and toss it into that arraylist. Most likely going to use a for each loop for that, just need to do some more research on that.
My question is how do I use this random object rand with a set probability for those three parties, and execute it? Anyone got any ideas?
EDIT: Bottom line is: How do I implement a 2/5 and a 1/5 probability for those three Parties, and then call the random object to give me a party based on those probabilities?
AFTER mre's Answer, I did this:
Random rand = new Random();
List<Party> parties = Arrays.asList(Party.DEMOCRAT, Party.DEMOCRAT, Party.REPUBLICAN, Party.REPUBLICAN, Party.INDEPENDENT);
and a little later on....
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 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);
}
}
Answered, new question : Using a foreach loop to add values from an arraylist, and then print them using accessors