Solidity
填充結構會引發錯誤
嗨,我正在嘗試在混音中執行此程式碼。它部署成功,但是每當我使用 addCustomer 函式添加客戶時,它都會顯示此消息“交易到 MyContract.addCustomer 掛起 … ”。之後,如果我嘗試與任何其他功能互動,它只會列印例如“呼叫 MyContract.totalRooms ”,然後瀏覽器視窗掛起。我可以知道是什麼問題。
pragma solidity ^0.6.0; contract MyContract { enum Statuses {Vacant,Occupied} uint internal counter = 0; event occupied (string cname, address raddr); uint public constant totalRooms = 5; struct Room{ address roomAddress; Statuses roomStatus; } mapping(uint => Room) public rooms; function roomInfo() public { rooms[1] = Room(0x33c5E8069F3F5b653fEDdE8c628B1e0DE48382a1,Statuses.Vacant); rooms[2] = Room(0x88789bB3d6B1eF931d3DF5aB008A38F86EA3da8d,Statuses.Vacant); rooms[3] = Room(0xDaEf09dE138de7C27f1a43cA6c544c1a6A50BAf9,Statuses.Vacant); rooms[4] = Room(0xC72C577e4450E4AAF9eaf2FF3ff6b3eC597F894b,Statuses.Vacant); rooms[5] = Room(0xF68af2bAC4c9Db4a27186C6382eAD0c0BA04638F,Statuses.Vacant); } // Mappings mapping(uint => Customer) public customers; struct Customer { address _address; string name; address room; } constructor() public { } function addCustomer(address _add, string memory _name) public { address _room; while(counter<=totalRooms){ for(uint i =0; i< totalRooms;i++){ if(rooms[i].roomStatus==Statuses.Vacant) _room = rooms[i].roomAddress; else i++; } customers[counter+1] = Customer(_add, _name,_room); } emit occupied(_name,_room); } }
該
addCustomer
函式有一個無限循環while 循環
counter
內部永遠不會被修改while(counter<=totalRooms){ for(uint i =0; i< totalRooms;i++){ if(rooms[i].roomStatus==Statuses.Vacant) _room = rooms[i].roomAddress; else i++; } customers[counter+1] = Customer(_add, _name,_room); }
似乎應該在那裡使用 if
if (counter < totalRooms) { for (uint i = 0; i< totalRooms; i++){ if (rooms[i].roomStatus == Statuses.Vacant) { _room = rooms[i].roomAddress; break; } } counter += 1; customers[counter] = Customer(_add, _name,_room); }