共計 1596 個字符,預計需要花費 4 分鐘才能閱讀完成。
要實現一個 Java 投票統計程序,可以按照以下步驟進行:
- 定義一個投票類,包含候選人的姓名和得票數。
public class Candidate {private String name;
private int votes;
public Candidate(String name) {this.name = name;
this.votes = 0;
}
public String getName() {return name;
}
public int getVotes() {return votes;
}
public void addVote() {votes++;}
}
- 創建一個候選人列表,并初始化候選人對象。
List<Candidate> candidates = new ArrayList<>();
candidates.add(new Candidate(" 候選人 1 "));
candidates.add(new Candidate(" 候選人 2 "));
candidates.add(new Candidate(" 候選人 3 "));
- 接收用戶的投票輸入,根據輸入的候選人姓名增加相應候選人的得票數。
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
for (Candidate candidate : candidates) {if (candidate.getName().equals(input)) {candidate.addVote();
break;
}
}
- 統計所有候選人的得票數,并輸出結果。
for (Candidate candidate : candidates) {System.out.println(candidate.getName() + " 得票數:" + candidate.getVotes());
}
完整的代碼如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class VotingSystem {public static void main(String[] args) {List<Candidate> candidates = new ArrayList<>();
candidates.add(new Candidate(" 候選人 1 "));
candidates.add(new Candidate(" 候選人 2 "));
candidates.add(new Candidate(" 候選人 3 "));
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
for (Candidate candidate : candidates) {if (candidate.getName().equals(input)) {candidate.addVote();
break;
}
}
for (Candidate candidate : candidates) {System.out.println(candidate.getName() + " 得票數:" + candidate.getVotes());
}
}
static class Candidate {private String name;
private int votes;
public Candidate(String name) {this.name = name;
this.votes = 0;
}
public String getName() {return name;
}
public int getVotes() {return votes;
}
public void addVote() {votes++;}
}
}
這樣,當用戶輸入候選人的姓名時,程序會自動增加相應候選人的得票數,并在最后輸出所有候選人的得票數。
丸趣 TV 網 – 提供最優質的資源集合!
正文完