本帖最后由 thepoy 于 2020-7-12 09:34 编辑
代码如下:
pragma solidity >=0.4.21;
contract Voting {
struct voter {
address voterAddress;
uint tokenNum;
uint[] tokensVoteForCandidates;
}
uint public totalTokens;
uint public tokenBalance;
uint public tokenPrice;
bytes32[] public candidateList;
mapping(bytes32=>uint) public votesReceived;
mapping(address=>voter) public voterInfo;
constructor(uint totalSupply, uint price, bytes32[] memory candidateNames) public {
totalTokens = totalSupply;
tokenBalance = totalSupply;
tokenPrice = price;
candidateList = candidateNames;
}
function voteForCandidate(bytes32 candidate, uint voteTokens) public {
uint index = indexOfCandidate(candidate);
require(index!=uint(-1));
if(voterInfo[msg.sender].tokensVoteForCandidates.length==0){
for (uint i = 0; i < candidateList.length; i++){
voterInfo[msg.sender].tokensVoteForCandidates.push(0);
}
}
uint availableTokens = voterInfo[msg.sender].tokenNum - totalUsedTokens(voterInfo[msg.sender].tokensVoteForCandidates);
require(availableTokens>=voteTokens);
votesReceived[candidate] += voteTokens;
voterInfo[msg.sender].tokensVoteForCandidates[index] += voteTokens;
}
function indexOfCandidate(bytes32 candidate) public view returns(uint){
for (uint i = 0; i < candidateList.length; i++){ // warning在这里:i++无法达到
if(candidate==candidateList[i]){
return i;
}
return uint(-1);
}
}
}
写的时候就有注意到这个warning,但想到warning嘛,又不是error,就没管它,没想到部署合约后无法正常动行,经排查就是这个warning的原因。
在用indexOfCandidate查找指定candidate时,candidateList里只有一个元素,但constructor初始化时,给candidateList赋值的是有3个元素的bytes32[],但在indexOfCandidate里的candidateList却只有第一个元素,所以无法取到其他元素,所以导致整个程序运行错误。
请问我该如何调整修改代码,能够使indexOfCandidate里的candidateList是我初始化的candidateList?
return uint(-1);在循环体外,没注意到 |