Javaで投票統計プログラムを実装する方法を教えてください
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"));
- ユーザーの投票入力を受信し、入力された候補者の得票に1を加える。
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++;
}
}
}
このようにユーザー候補者の名前を入力すると、その候補者に自動的に投票が行われ、最終的に全員の得票数が発表されます。