第一个投票合约

pragma solidity >=0.8.0;

contract Voting {
    //该合约一开始启动的时候,就把所有候选人定死
    //          ↓表示private
    string[]   internal nameList;
    //                                     ↓ 在github的solidity->typecheck源码中看到的
    constructor(string[] memory names) {//waring:构造函数输入的参数只能是memory(值类型)不能是storage(引用类型)
        nameList=names;
    }
    
    //比较两个字符串是否相等
    function compare(string memory a, string memory b) pure internal returns (bool) {
        if (bytes(a).length != bytes(b).length) {
            return false;
        }
        for (uint i = 0; i < bytes(a).length; i ++) {
            if(bytes(a)[i] != bytes(b)[i]) {
                return false;
            }
        }
        return true;
    }
    
    //字典  unsigned Int, 记住字典如果key是string,那么key是不能填变量的      
    mapping(uint=>uint) internal votesReceived;
    
    //返回该用户的下标
    function num(string memory name) view internal returns(uint){
        for(uint i = 0; i< nameList.length; i++){
            if(compare(name,nameList[i]))    return i;
        }
        return 9999;
    }
    
    
    
    //该人票数+1
    function vote(string memory name) public{
        uint index=num(name);
        require(index!=9999);//需要里面的满足才能继续 //异常处理,相当于 if(里面的为false) return 
        votesReceived[index]+=1;
        
    }
    //查看该人的票
    function totalVotesFor(string memory name) view public  returns(uint){
        uint index=num(name);
        require(index!=9999);
        return votesReceived[index];
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值