要实现一个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++;
}
}
}
这样,当用户输入候选人的姓名时,程序会自动增加相应候选人的得票数,并在最后输出所有候选人的得票数。