要實現一個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++;
}
}
}
這樣,當用戶輸入候選人的姓名時,程序會自動增加相應候選人的得票數,并在最后輸出所有候選人的得票數。