4

I have created following method in contract with the strcuture

contract testContract{
  Student[] public students;

  struct Student{
    string name;
    uint256 age;
  }

  function addStudent(string name, uint256 age){
    students[students.length++] = Student({name:name,age:age});
  }
}

now using ethereumj I call the function on the deployed contract as follows:

studentContract.callFunction("addStudent","ajay", 15);
Object[] objectArray = studentContract.callConstFunction("students");

The object array is of length 2 and contains the values "ajay" and 15, which is fine.

but when I call the function second time as follows :

studentContract.callFunction("addStudent","ajay", 15);
Object[] objectArray = studentContract.callConstFunction("students");
studentContract.callFunction("addStudent", "narendra", 17);
objectArray = studentContract.callConstFunction("students");

This time the object array should hold 4 values, i.e "ajay",15,"narendra",17.

But it still keeps the older values only, and length is not increased, objectArray has size 2 with values "ajay",15.

Please somebody provide answer to this.

  • Did you try calling it with an index? ie. Object[] objectArray = studentContract.callConstFunction("students", 0); I don't know how ethereumj works but students is an array. – Ismael Jun 13 '16 at 18:33
  • Ismael you really made me smile. This worked quite well. – Ajay Bhojak Jun 13 '16 at 19:04
  • Solidity can have multiply return values, thus array is here – Anton Nashatyrev Jun 28 '16 at 3:31
2

Would this work?

students.push(Student({name:name,age:age}));
  • Where should I write the above code? – Ajay Bhojak Jun 13 '16 at 17:52
  • instead of students[students.length++] = Student({name:name,age:age}); – Roland Kofler Jun 13 '16 at 17:53
  • should I write it students.push(Student({name:name,age:age})); in place of students[students.length++] = Student({name:name,age:age}); – Ajay Bhojak Jun 13 '16 at 17:53
  • yes indeed, as said... – Roland Kofler Jun 13 '16 at 17:55
  • 1
    @Ronald Kofler you provided new way to push items into arrays so upvote for you :) – Ajay Bhojak Jun 24 '16 at 15:30
2

Object[] objectArray = studentContract.callConstFunction("students", index);

Where index can be any whole number value specifying the index of the items in the student array.

So if you want to access 2nd item on the array, you would require index=1 as the value of index.

Answer on behalf of @Ismael

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.