'Using objects in an array independently
I have an array of objects of different types and i want to pick only 1 object from the array and add it up. For example i have an array with 4 users that all have connectiontime as an object and i want to add up all their connectiontime alone without the other objects in the array, how do i pick out the connection time after iterating through the array and then return the sum of connection time. This is the array and the code meant to be implemented with the array.code to use the arrayarray with object
Solution 1:[1]
So here is how I view and how I understand the problem : You want to have all the connection time of all the user. You method that iterates should not return an object of ConnectionTime but just a float. But that is just how I see it from the very few informations you have given us.
1- You have 2 classes : User and ConnectionTime
User class :
class User{
ConnectionTime connectionTime;
public User(){
// Some code to construct your object...
}
public float getConnectionTime(){
return this.connectionTime.getConnectionTime();
}
}
ConntectionTime class :
class ConnectionTime{
float time;
public ConnectionTime(){
//Some code to construct your object
}
public getConnectionTime(){
return this.time;
}
}
And them all you have to do now is iterate over the Users list :
float totalConnectionTime = 0;
public getTotalConnectionTimeOfUsers(){
for(int i = 0; i < users.length ; i++){
totalConnectionTime += users[i].getConnectionTime();
}
return totalConnectionTime;
}
If this is not what you expected at all, feel free to add more information for us to help you !
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KévenChamp |
