0

Good evening people,

I have a method that creates, populates, and returns an array to the function call as so:

 public double[] getTotalDistances(){
  double[] distance;
   distance = new double[3];


    for(Activity r: diary ){

        if(r instanceof Run){
           distance[0] += r.getDistance(); 
        }
    }
   return distance;

}

and i can't seem to find a way to access this returned array to print it out in the main method, i have tried this: (where m is the object i have instantiated)

for(int i = 0; i< m.getTotalDistances().length; i++){

        System.out.println(m.getTotalDistances().distance[i]);
    }

this says it cannot find the variable distance.

i am aware that i can do something like:

 for(double i: m.getTotalDistances()){
      System.out.println(i);
}

this will print out the returned array, however, i would like to know how to do it in the "classic" way.I know that this must be extremely novice, but i couldn't find an answer. Any kind of help will be greatly appreciated.

3 Answers 3

2

It should be m.getTotalDistances()[i] and not m.getTotalDistances().distance[i]

Sign up to request clarification or add additional context in comments.

2 Comments

Oh i see, thank you, that works like a charm, there seems to be a minimum time to accept an answer so i will accept the answer in 8 minutes
This will calculate getTotalDistances() every time again in the loop and is prone to concurrency problems.
2

Use a variable to store it before iterating.

double[] distance = m.getTotalDistances();
for(int i = 0; i < distance.length; i++){
        System.out.println(distance[i]);
}

Your approach would call your getTotalDistances() method over and over inside the loop. You only need it once to work with.

You get this error

this says it cannot find the variable distance.

because the variable distance is only known in the scope of your method getTotalDistances() and thus you cannot use it outside of that (and it wouldn't make sense either).

Comments

1

The way it is written, distance is not defined. You will need to create a pointer the the returned value if you want to reference it.

double[] distance = getTotalDistances();
for(int i = 0; i < distance.length; i++) {
    System.out.println(distance[i]);
}

Also, as it is written, any values other than the first will always be 0, and an accumulator makes more sense.

Another thing to note is that, as it is written, getTotalDistances() will run twice on each iteration of your for loop; once for the condition and again for the println(). If you were to scale this concept to a larger use case, the performance implications would be huge.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.