在 java 中传递数组

Passing arrays in java

我知道我不能像现在这样传递数组。如果是这样,我需要通过引用传递吗?问题在底部供参考

import java.util.Scanner;
public class MethodsArrays {

    public static int[] fillArray() {
        Scanner scan = new Scanner(System.in);
        int size = scan.nextInt();
        int array[] = new int[size];
        int pos=0;

        for(int i=0; i<array.length; i++) {
            pos=i+1;
            System.out.println("Enter element " + pos);
            array[i]=scan.nextInt();
        }
        return array;
    }

    public static int sumArray(int [] array) {
        int sum=0;

        for(int i=0; i<array.length-1; i++) {
            sum=array[i]+array[i+1];
        }
        return sum;
    }

    public static int avgArray(int [] array) {
        int avg=0;
        int sum = sumArray(array);
        avg = sumArray(array)/array.length-1;
        return avg;
    }

    public static void printArray(int [] array) {
        for(int i=0; i<array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }

    public static void main(String[] args) {
        fillArray();
        System.out.println("Sum=" + sumArray(array));
        System.out.println("Average=" + avgArray(array));
        printArray(array);
    }
}

Write a Java program, called MethodsArrays that has 4 static methods called fillArray(), sumArray(), avgArray(), and printArray(). The fillArray() method should be called from the main method. The fillArray() method should use a Scanner to take in a number representing the length of the array and then read in numbers to fill the array. The sumArray() method should take an int array as its input parameter and returns an integer value that is the sum of all the elements in the array. The avgArray() method should take an int array as its input parameter and returns an integer value that is the average of all the elements in the array. The printArray() method should take an int array as its input parameter and has no return value. It should then print out the elements of the array on the same line separated by a space (“ “). All methods should work for integer arrays.

您的代码看起来没问题。您只需要将 fillArray() 的结果分配给一个变量,以便将此结果用于其他方法。

看起来像:

 int[] array = fillArray();
 System.out.println("Sum=" + sumArray(array));
 System.out.println("Average=" + avgArray(array));
 printArray(array);