Using your favorite IDE (e.g., Eclipse or NetBeans), create a new Java application (project) named CPS151_Lab3, or, if you are using DrJava, create a folder named CPS151_Lab3.
Then, to either your project or folder, add:
Add to the VotingMachine class:
Lab 3.2
Switch back to the main class and copy/paste the following below code to the main method:
public static void main(String[] args)
{
VotingMachine machine = new
VotingMachine();
// randomly add 1,000 votes for either
party
for (int i=1; i<=1000; i++)
{
if (Math.random() < 0.5) {
machine.voteDem(); }
else { machine.voteRep();
}
} // end for loop
// show results of voting
System.out.printf("The Democratic candidate won
%d votes, ", machine.getDemVotes());
System.out.printf("while the Republican
candidate won %d votes, so ...\n", machine.getRepVotes());
System.out.printf("The %s candidate won the
election!\n", machine.getWinner());
} // end main
Thanks for the question. Here is the simple sort class VotingMachine.java class. I am embedded the main() method inside and ran, and its working all good:! Here is the code. ======================================================================================== public class VotingMachine { private int democratVotes; private int republicVotes; public VotingMachine() { democratVotes = 0; republicVotes = 0; } public void clear(){ democratVotes=0; republicVotes=0; System.out.println("Reset done."); } public void voteDem(){ democratVotes+=1; } public void voteRep(){ republicVotes+=1; } public int getDemVotes() { return democratVotes; } public int getRepVotes() { return republicVotes; } public String getWinner(){ if(democratVotes>republicVotes){ return "Democrat"; }else if(democratVotes<republicVotes){ return "Republican"; }else{ return "Neither!"; } } public static void main(String[] args) { VotingMachine machine = new VotingMachine(); // randomly add 1,000 votes for either party for (int i=1; i<=1000; i++) { if (Math.random() < 0.5) { machine.voteDem(); } else { machine.voteRep(); } } // end for loop // show results of voting System.out.printf("The Democratic candidate won %d votes, ", machine.getDemVotes()); System.out.printf("while the Republican candidate won %d votes, so ...\n", machine.getRepVotes()); System.out.printf("The %s candidate won the election!\n", machine.getWinner()); } // end main }
===================================================================
Get Answers For Free
Most questions answered within 1 hours.