Quantcast
Viewing all articles
Browse latest Browse all 207

Return value only

I want to print the mean and the median calculated from an array of integers. Here is my code:

// I create and populate the int arraypublic static int[] populateArray(Scanner input) {    int[] array = new int[input.nextInt()];    for (int i = 0; i < array.length; i++) {        array[i] = input.nextInt();    }    return array;}// I create a method which takes as formal parameter an array of int an prints the result of mean from the arraypublic static void printMean(int[] populatedArray) {    double mean = 0;    for (int aPopulatedArray : populatedArray) {        mean += aPopulatedArray;    }    mean /= populatedArray.length;    System.out.println(mean);}// I create a method which takes as formal parameter an array of int an prints the result of median from the arraypublic static void printMedian(int[] populatedArray) {    Arrays.sort(populatedArray);    double median;    if (populatedArray.length % 2 != 0) {        median = populatedArray[populatedArray.length / 2];    } else {        median = (populatedArray[populatedArray.length / 2] + populatedArray[populatedArray.length / 2 - 1]) / 2;    }    System.out.println(median);}

In Main, I first want to call the populateArray() method. I will populate my array. Then, how can I pass as a formal parameter, to the other 2 methods(printMean() and printMedian()) only the array from populateArray()?

I don't want to do this, each time I use the array from populateArray() method:

int[] array = new int[input.nextInt()];for (int i = 0; i < array.length; i++) {    array[i] = input.nextInt();}

I want to populate an array an then use those values in both print methods.

Thanks in advance!


Viewing all articles
Browse latest Browse all 207

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>