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

