我是java初学者,我的投票系统有这些代码:
public void Result_Election(){
int vote1=Vote_President();
String pres1="Theo";
String pres2="William";
String pres3="Maxon";
String pres4="Douglas";
int n1=0, n2=0, n3=0, n4=0;
try{
PrintWriter i=new PrintWriter(new FileWriter("voting_score.txt", true));
if (vote1==1){
int[] addVotes = {1};
for (int add : addVotes){
result[add-1]+=1;
n1=result[add-1];
}
i.println(pres1+" "+n1);
}
else if (vote1==2){
int[] addVotes = {2};
for (int add : addVotes){
result[add-1]+=1;
n2=result[add-1];
}
i.println(pres2+" "+n2);
}
else if (vote1==3){
int[] addVotes = {3};
for (int add : addVotes){
result[add-1]+=1;
n3=result[add-1];
}
i.println(pres3+" "+n3);
}
else if (vote1==4){
int[] addVotes = {4};
for (int add : addVotes){
result[add-1]+=1;
n4=result[add-1];
}
i.println(pres4+" "+n4);
}
i.close();
}catch (Exception e){
}
}
我的问题是输出。每次我为一位候选人添加选票时,它都会添加另一个名字及其增加的选票。但我想要的只是每个候选人的一个名字,每次我为一名候选人添加选票时,它不会添加另一个名字。只是投票数。请帮忙
最佳答案
为了避免所有这些变量和 if-else block ,我们可以简单地做一些类似的事情 -
Map<String, Integer> candidates = new HashMap<String, Integer>();
candidates.put("Theo", 0);
candidates.put("William", 0);
candidates.put("Maxon", 0);
candidates.put("Douglas", 0);
switch (vote1)
{
case 1:
candidates.put("Theo", candidates.get("Theo")+1);
break;
case 2:
candidates.put("William", candidates.get("William")+1);
break;
case 3:
candidates.put("Maxon", candidates.get("Maxon")+1);
break;
case 4:
candidates.put("Douglas", candidates.get("Douglas")+1);
break;
}
它将更容易理解和调试。这只是一个例子。您可以按照您想要的方式使用它。
我没有看到“int[] addVotes = {1};”有任何用途并迭代它,因为这总是只包含一个值?你来这里的目的是什么?另外你是如何初始化“结果”的?
[更新]按照自己的方式去做并减少不必要的细节:
public void Result_Election(){
int vote1 = Vote_President();
String[] candidateArray = {"Theo", "William", "Maxon", "Douglas"};
String fileAbsolutePath = "C:/voting_score.txt";
try
{
int[] result = getStorredResult(fileAbsolutePath, candidateArray);
PrintWriter pw = new PrintWriter(new FileWriter(fileAbsolutePath));
result[vote1-1] = result[vote1-1]+1;
for (int i = 0; i < candidateArray.length; i++) {
pw.println(candidateArray[i]+" "+result[i]);
}
pw.flush();
pw.close();
}
catch (Exception e)
{
e.printStackTrace(); // better write in log
}
}
private int[] getStorredResult(String fileName, String[] candidateArray) throws NumberFormatException, IOException {
String currentLine = null;
int[] result = new int[candidateArray.length];
File file = new File(fileName);
if(file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
while((currentLine = br.readLine()) != null) {
for (int i = 0; i < candidateArray.length; i++) {
if(currentLine.startsWith(candidateArray[i])) {
result[i] = Integer.parseInt(currentLine.split(" ")[1]);
break;
}
}
}
br.close();
}
return result;
}
关于java - 我的投票系统已经很好但是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29100356/