简体   繁体   中英

Accessing array in a return method

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.

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).

应该是m.getTotalDistances()[i]而不是m.getTotalDistances().distance[i]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM