Java Case 6: Student Voting System

 
 

Idea:

student voting system

Implement voting procedure, total class size is 100, each person has one vote
Successful voting prompts "Vote successfully, thank you for your support"
Duplicate voting prompt "Please do not vote repeatedly"
When the total number of votes reaches 100 or the voting ends subjectively, the number of voting students and the voting results will be counted at the same time.

1. Student Voter
Name
Maximum number of votes
Current number of votes
Vote

2. Number of votes, static member variables, private static int count
Ensure there is only one copy of the data

3. To prevent students from voting repeatedly, the information of students participating in voting must be saved. A collection can be used to store student objects that have voted.
private static Set<Voter>voters = new HashSet<Voter>();

4. Write test classes

Code:

Code structure:

Test class:

public class Test06 {
    public static void main(String[] args) {
        Voter v1 = new Voter("周自珩");
        Voter v2 = new Voter("夏习清");
        Voter v3 = new Voter("shoogy");
        v1.voterFor("同意");
        v1.voterFor("反对");
        v2.voterFor("反对");
        v3.voterFor("同意");

        v1.printResult();
 //        v2.printResult();
 //        v3.printResult();



    }
}

 

Student Voter:
package base.base006;
/*
1.学生类Voter
姓名 name
最大投票数 MAX_COUNT
当前投票数 count
投票意见 answer

2.票次数,静态成员变量,private static int count
保证数据只有一份

3.防止学生重复投票,必须保存参与投票的学生信息,可采用一个集合来存放已经投票的学生对象。
private static Set<Voter>voters = new HashSet<Voter>();
 */

import java.util.HashSet;

public class Voter {
    private String name;
    private static final int MAX_COUNT = 100;
    private static int count;
    private static HashSet<Voter> voters = new HashSet<>();
    private String answer;

    public Voter(String name) {
        this.name = name;
    }

    //投票
    public void voterFor(String answer){
        if(count == MAX_COUNT){
            System.out.println("投票数已达上限!");
            return;
        }

        if(voters.contains(this)){
            System.out.println(name+"  请勿重复投票");
        }else{
            this.answer = answer;
            count ++;
            voters.add(this);
            System.out.println("投票成功,感谢您的支持!");
        }

    }

    //投票结果统计
    public void printResult(){
        System.out.println("已有"+count+"人参与投票");
        System.out.println("参与投票的结果如下:");
        for (Voter voter:voters){
            System.out.println(voter.name+":"+voter.answer);
        }
    }




}

Guess you like

Origin blog.csdn.net/weixin_54446335/article/details/131165396