溫馨提示×

java投票統計程序怎么實現

小億
179
2023-11-15 22:45:50
欄目: 編程語言

要實現一個Java投票統計程序,可以按照以下步驟進行:

  1. 定義一個投票類,包含候選人的姓名和得票數。
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++;
    }
}
  1. 創建一個候選人列表,并初始化候選人對象。
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;
    }
}
  1. 統計所有候選人的得票數,并輸出結果。
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++;
        }
    }
}

這樣,當用戶輸入候選人的姓名時,程序會自動增加相應候選人的得票數,并在最后輸出所有候選人的得票數。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女