我想打印从整数数组计算出的平均值和中位数。这是我的代码:

// I create and populate the int array
public 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 wich takes as formal paramether an array of int an prints the result of mean from the array

public 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 wich takes as formal paramether an array of int an prints the result of median from the array

public 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);
}


在Main中,我首先要调用populateArray()方法,然后填充数组。然后,如何仅将printMean()中的数组作为形式参数传递给其他2种方法(printMedian()populateArray())?

每次使用populateArray()方法中的数组时,我都不想这样做:

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


我想填充一个数组,然后在两种打印方法中使用这些值。

提前致谢 !

最佳答案

假设逻辑是正确的,那么我的代码结构不会有太大问题。只需获取填充的数组,然后在其他两种方法中使用它即可:

public static void main(String[] args) {
    int[] array = populateArray(new Scanner(System.in));
    printMean(array);
    printMedian(array);
}


您应该避免这种情况,因为您的辅助方法读取但不修改输入数组。这意味着您可以继续将初始数组传递给后续方法。

关于java - 仅返回值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41933406/

10-12 01:42