in java The results from the mayor\'s race have been reported by each precinct a
ID: 3763182 • Letter: I
Question
in java
The results from the mayor's race have been reported by each precinct as follows:
Candidate Candidate Candidate Candidate Winner Runoff
Precinct A B C D
1 192 48 206 37
2 147 90 312 21
3 186 12 121 38
4 114 21 408 39
5 267 13 382 29
Write a program to do the following:
a. Read the raw vote totals from a data file that contains one row for each precinct.
b. Display the table with appropriate headings for the rows and columns.
c. Compute and display the total number of votes received by each candidate and
the percent of the total votes cast.
d. If any one candidate received over 50% of the votes, the program should print, in the last column, a message declaring that candidate the winner.
e. If no candidate received 50% of the votes, the program should print a message
declaring a run-off between the two candidates receiving the highest number of
votes; the two candidates should be identified by their letter names.
f. For testing, run the program with the above data, and also with another
data file where Candidate C receives only 108 votes in precinct 4.
Data file:
(precinct, candiadateAvotes, , candiadateBvotes, candiadateCvotes, candiadateDvotes
1 192 48 206 37
2 147 90 312 21
3 186 12 121 38
4 114 21 408 39
5 267 13 382 29
Explanation / Answer
a.
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Lab1 {
public static void main(String[] args) {
Scanner voteFile = null; // data file
// open the word file
try {
voteFile = new Scanner(new FileInputStream("lab10data.txt"));
}
catch (FileNotFoundException e) {
System.out.println("File not found or not opened.");
System.exit(0);
}
VotingResults results = new VotingResults(voteFile);
results.displayReport();
results.displayTotals();
results.displayWinner();
}
}
b.
public void run()
{
int timestamp = 0;
int iterationsBeforeFull = 60; // Fifteen minutes
int iteration = 0;
if ( results != null )
{
servThread.start();
while(true)
{
sleep(30);
try
{
SQLStmt nn;
// After so many iterations, resend all data...
if (iteration >= iterationsBeforeFull) {
nn = election.sql("select * from election order by Âstate,candidate");
synchronized (results)
{
results = nn;
}
servThread.sendToUsers(
formatResults("RESULTS", results));
iteration = 0;
} // end full if
else {
// Otherwise just check timestamps...
String partialSQL =
"select * from election where updated > '" +
timestampToChar(timestamp) +
"' order by state,candidate";
nn = election.sql(partialSQL);
// Make sure a valid number of rows is returned...
if ((nn.numRows() > 0) && ((nn.numRows()%2) == 0) ) {
// Send data and update timestamp...
servThread.sendToUsers(
formatResults("RESULTS", nn));
++timestamp;
}
++iteration;
}
}
catch (DBException de)
{
System.out.println("Error: " + de);
}
}
}
}
c.
public class Election extends Applet implements LiveDataNotify
{
private static final int SPACING = 70;
private boolean init = false;
DGTpclient ct = null;
int destPort;
String destHost = null;
String numUsers = "Unknown at this time";
String users = null;
String results[][];
int nRows = 0, nCols = 0;
// Place canvas drawing objects...
SummaryCanvas sc;
StateBreakdownCanvas states;
Checkbox graphView,textView;
Panel p;
public void init()
{
if ( init == false )
{
// Initialize network connections...
init = true;
String strPort = getParameter("PORT");
if ( strPort == null )
{
System.out.println("ERROR: PORT parameter is missing");
strPort = "4545";
}
destPort = Integer.valueOf(strPort).intValue();
destHost = getDocumentBase().getHost();
// Initialize AWT components...
// Do basic setup...
setLayout(new BorderLayout());
// Add panel to set views...
p = new Panel();
CheckboxGroup cg = new CheckboxGroup();
graphView = new Checkbox("Graphical View",cg,false);
textView = new Checkbox("Text View",cg,true);
p.add(graphView);
p.add(textView);
add("North",p);
sc = new SummaryCanvas(this);
// Show state breakdowns...
states = new StateBreakdownCanvas(this);
// Create update thread...
Thread t = new ElectionUpdater(this);
t.start();
Dimension d = size();
FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(getFont());
int height = sc.getHeight() + states.getHeight() + (2 * fm.getHeight());
resize(d.width,height);
show();
}
}
public void update(Graphics g)
{
paint(g);
}
public synchronized void paint(Graphics g) {
if (!(ElectionTable.getElectionTable().ready()) )
return;
Dimension d = size();
int height = g.getFontMetrics(getFont()).getHeight();
int y = 2 * height;
y = sc.paint(g,0,y,d.width);
y += states.paint(g,0,y,d.width,d.height - y);
g.drawString("Registered Users: " + getUsers(),
10,d.height - height);
}
public boolean action(Event ev,Object o) {
if (ev.target instanceof Checkbox) {
if (ev.target.equals(graphView)) {
states.setMode(StateBreakdownCanvas.GRAPHICS);
sc.setMode(SummaryCanvas.GRAPHICS);
}
else {
states.setMode(StateBreakdownCanvas.TEXT);
sc.setMode(SummaryCanvas.TEXT);
}
repaint();
}
return true;
}
d.
public String getDestHost()
{
return destHost;
}
public int getDestPort()
{
return destPort;
}
public synchronized void recvNewData(byte[] newDataBlock, boolean error)
{
if ( error )
{
ct.send("REFRESH");
return;
}
String cmd = new String(newDataBlock, 0);
StringTokenizer cmds = new StringTokenizer(cmd, " ");
String current = cmds.nextToken();
if (current.equals("CLIENTS"))
users = cmds.nextToken();
else if (current.equals("RESULTS"))
{
nRows = Integer.valueOf(cmds.nextToken()).intValue();
nCols = Integer.valueOf(cmds.nextToken()).intValue();
results = new String[nRows][nCols];
for ( int x = 0; x < nRows; x++ )
{
for ( int y = 0; y < nCols; y++ )
{
results[x][y] = cmds.nextToken("| ");
}
}
// Update the election table with the new data...
ElectionTable.getElectionTable().tableUpdate(nRows,results);
}
// QUERY response is unimplemented because
// this applet currently sends no QUERY commands
else if (current.equals("QUERY_RSP"))
{
}
}
public synchronized String getUsers()
{
if (users != null)
return users;
return numUsers;
}
public void start()
{
ct = new DGTpclient(this);
ct.start();
}
public void stop()
{
System.out.println("Election.stop()");
ct.terminate();
}
public void connectRefused()
{
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.