如何从静态方法返回数组?

时间:2017-01-31 06:54:33

标签: java arrays return

我正处于计算机编程的第一周,我需要弄清楚如何将数组返回到main。我希望外部for循环重复两个输入类型(赋值和实验室)的内部,然后我想将平均赋值和平均实验值作为数组返回到main。

import java.util.stream.*;
import java.util.Scanner;

public class Gr {
    public static void main(String [] args) {

    }

    public static void taskAvg() {
        Scanner stdin = new Scanner(System.in);
        int numberOfTasks = 7;
        String typeOfTask = "Assignment";
        int taskTotal = 10;
        double[] taskGrades = new double[11];

        for (int i = 1; i <=2; i++) {
            System.out.println("\nInput " + typeOfTask + " (maximum " + taskTotal + ")");
            for (int j = 1; j <= numberOfTasks; j++) {
                System.out.print(" #" + j + "==>");
                taskGrades[j] = stdin.nextDouble();
                if (taskGrades[j] > taskTotal || taskGrades[j] < 0) {
                    System.out.println("Oops! That's not right. Please try again.");
                    System.out.print(" #" + j + "==>");
                    taskGrades[j] = stdin.nextDouble();
                }
            }
            double taskSum = DoubleStream.of(taskGrades).sum();
            double taskAverage = taskSum / numberOfTasks;
            numberOfTasks = 10;
            typeOfTask = "lab";
            taskTotal = 1;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

首先,您需要更改函数的类型以返回数组。

public static double[] taskAvg(){
    double[] taskGrades = new double[11];

    ... // Do your stuff

    return taskGrades;
}

然后你需要将值赋给main中的变量。

public static void main(String [] args) {
    double[] result = taskAvg();
}