我是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){
}
}
我的问题是输出。每当我向一个候选人添加投票时,它将添加另一个名称及其增加的投票。但我想要的只是每个候选人一个名字,每次我把一个候选人的选票加起来,它就不会添加另一个名字。只是投票数。请帮忙
答案 0 :(得分:1)
为了避免所有这些变量和if-else阻止,我们可以简单地执行类似 -
的操作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;
}
理解和调试会更容易。这只是一个例子。您可以按照自己的方式使用它。
我没有看到使用&#34; int [] addVotes = {1};&#34;并迭代它,因为这总是只保留一个值?你的意图是什么?你是如何初始化&#34;结果&#34;?
的[更新] 以自己的方式行事并减少不必要的细节:
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;
}