我是一名初学者,并且在java方面没有多少经验。我对使用数组,if-else语句和循环编写代码的程序感到困惑。
作业是:
编写一个使用文件ElectionVotes.txt的程序,该文件包含州名和选举投票,以及文件ElectionData.txt,其中包含每个候选人的州名和总票数,以计算奥巴马获得的选举人票数。和罗姆尼在2012年大选中。您的程序应该使用状态名称构建一个查找表,另一个表格具有该状态的相关选举投票。输出应显示两个数字 - 每个候选人的总选举票数。
我试过这样做,但我不知道这是否有用。
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Electoral_Votes {
public static void main(String[] args) {
String str, filename, filename2;
double[] States = new double[51];
int[] ObamaVote = new int[51];
int[] RomneyVote = new int[51];
int high, low, high2, low2, EV;
double Total, sum = 0;
int i = 0;
Scanner keyboard = new Scanner(System.in);
try {
Scanner inputFile = new Scanner(new File("ElectionVotes.txt"));
str = inputFile.nextLine();
while (inputFile.hasNext()) {
str = inputFile.next();
States[i] = inputFile.nextDouble();
EV = inputFile.nextInt();
for (i = 0; i <= 51; i++) {
RomneyVote = getRomneyV();
ObamaVote = getObamaV();
if (RomneyVote > ObamaVote) {
RomneyVote[i] += EV;
}
}
}
} catch (IOException e) {
System.out.println("File not found");
}
}
public static double[] getElectionData() {
double[] States = new double[51];
int[] ObamaVote = new int[51];
int[] RomneyVote = new int[51];
int i = 0;
try {
Scanner inputFile = new Scanner(new File("ElectionData.txt"));
String str = inputFile.nextLine();
while (inputFile.hasNext()) {
str = inputFile.next();
States[i] = inputFile.nextDouble();
ObamaVote[i] = inputFile.nextInt();
RomneyVote[i] = inputFile.nextInt();
}
} catch (IOException e) {
System.out.println("File not found");
}
return States;
}
public static int[] getRomneyV() {
double[] States = new double[51];
int[] ObamaVote = new int[51];
int[] RomneyVote = new int[51];
int i = 0;
try {
Scanner inputFile = new Scanner(new File("ElectionData.txt"));
String str = inputFile.nextLine();
while (inputFile.hasNext()) {
str = inputFile.next();
States[i] = inputFile.nextDouble();
ObamaVote[i] = inputFile.nextInt();
RomneyVote[i] = inputFile.nextInt();
}
} catch (IOException e) {
System.out.println("File not found");
}
return RomneyVote;
}
public static int[] getObamaV() {
double[] States = new double[51];
int[] ObamaVote = new int[51];
int[] RomneyVote = new int[51];
int i = 0;
try {
Scanner inputFile = new Scanner(new File("ElectionData.txt"));
String str = inputFile.nextLine();
while (inputFile.hasNext()) {
str = inputFile.next();
States[i] = inputFile.nextDouble();
ObamaVote[i] = inputFile.nextInt();
RomneyVote[i] = inputFile.nextInt();
}
} catch (IOException e) {
System.out.println("File not found");
}
return ObamaVote;
}
}