Renuz
Renuz

Reputation: 1657

How can I add up values of an array object?

I have an array that created 5 objects. Each object has two strings and a int. Lets call the int "number". How can i add up the "number's" of each object into a final number, assume that the numbers change so i cannot simply just put 5 + 3 etc.. For example

          Question question[] = new Question[5];

 public Constructor()
{
    String1 = "null";
    Sting2 = "null";
    number = 0;
}

SO i have five objects that look like this, they all have a different value. Number refers to a score, So if the user does something right, the number will be added to a variable, i need to know how to add up the 5 variables when i execute the 5 objects in something like.

  for (i=0; i < Question.length; i++)
 {
   object.dostuff
}

Upvotes: 1

Views: 935

Answers (3)

use map to extract the numbers from the list of tuples then use reduce to accumulatively sum the numbers.

list=[("1 this is sentence 1","1 this is sentence 2",1),("2 this is sentence 1","2 
this is sentence 2",2),("3 this is sentence 1","3 this is sentence 2",3)]
numbers=map(lambda x: x[2],list)
result=reduce(lambda x,y: x+y,numbers)
print(result)

output:

6

Upvotes: 0

Newtopian
Newtopian

Reputation: 7722

Many things have to happen first:

  1. Initialize the array: seems you got that one covered.
  2. Initialize objects within the array: Make sure every cell of your array actually contains a question instance (or to be more precise: a reference to a Question instance).
  3. Iterate over the array: here your loop seems to go over the class (Question, with capital Q) but you need to iterate over the array (question with a small q). Piece of advice, since the variable question here represents an array of question it would make more sense if you make your name plural (questions) to help illustrate that this is an array. Basic rule is to make the name as explicit as possible, so questionArray would be an even better name. Past a certain point it's a question of taste. Rule of thumb is that if you have to look at the declaration of the variable then it's probably not named correctly.
  4. access methods, properties etc of the objects: when iterating over the array you need to access the right index (questions[i]) then access the members of this object (questions[i].doStuff). If you aim for OOP (which I assume is the point here) then you may want to make the obvious operations as functions of your Question class. Then simply call this function with the proper parameter (questions[i].setNumber(i)). It all depends on what you need it to do.

Hope this helps (if this is a homework related question you should tag it as such, that would maximize your chance to get help here).

Upvotes: 2

lukecampbell
lukecampbell

Reputation: 15256

Don't use Question.length, use question.length

Add an accessor method and a method to increment the scores.

Upvotes: 1

Related Questions