使阵列在多种方法中工作?

时间:2014-12-13 20:17:08

标签: java arrays

我目前正在学校做一个项目,它涉及从.txt文件中读取整数并将它们输入到数组中。这些整数将代表团队在一年内生产的产品数量。然后,我必须计算平均生产力,最高等...

到目前为止一切进展顺利,我知道如何做到这一点,我唯一不确定的是如何使数组在其他方法中工作,以便我可以计算平均值。这是我到目前为止的代码。关于我尚未编码的菜单有一些评论,但希望您能看到我想要做的事情,如果他们想要查看平均,最高或最低生产率,请给用户一个选项。正在扫描的文件实际上只是一个.txt文件,其中有一个数字在自己的行上(每月1个)。

/**
 * @author  Jack Orr
 * @version 1.0
 * @since   10-12-2014 
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;

// Begin by importing the utilities allowing for scanners and reading from files

public class Assignment {

    // main method which will call the other methods, employ a switch to choose
    // methods

    public static void main(String args[]) throws FileNotFoundException {

        readStats2012();
        readStats2013();
    }

    public static void readStats2012() throws FileNotFoundException {

        // This method reads the values from a keyboard scanner and assigns them to an array

        System.out.println("Productivity for 2012\n");
        ArrayList<Integer> teams = new ArrayList<Integer>();
        int inTeam;

        Scanner in = new Scanner(new File("in2012.txt"));
        while (in.hasNextInt()) {
            inTeam = in.nextInt();
            teams.add(inTeam);
        }

        in.close();

        for (int i = 0; i < teams.size(); i++) {
            System.out.println("Team " + (i + 1) + "\t" + teams.get(i));
        }
    }

    public static void readStats2013() throws FileNotFoundException {

        // This method reads the values from a keyboard scanner and assigns them to an array

        System.out.println("\nProductivity for 2013\n");
        ArrayList<Integer> teams = new ArrayList<Integer>();
        int inTeam;

        Scanner in = new Scanner(new File("in2013.txt"));
        while (in.hasNextInt()) {
            inTeam = in.nextInt();
            teams.add(inTeam);
        }

        in.close();

        for (int i = 0; i < teams.size(); i++) {
            System.out.println("Team " + (i + 1) + "\t" + teams.get(i));
        }   

    }
    static void calculateandDisplay(){

        // This will be a menu option to calculate the average, the highest and the lowest

        }

    public static double calculateAverage(){

        double average = 0;
        if(i = 0; i < teams.length; i++){

        }
        return average;

    }
}

2 个答案:

答案 0 :(得分:0)

我建议你返回列表并将它们保存为局部变量,并将这些变量作为参数传递给你想要调用的方法。

答案 1 :(得分:0)

我建议你将两种读取方法重构为一种参数化方法:

public static void readStats(int year) throws FileNotFoundException {
    ...
    Scanner in = new Scanner(new File("in" + year + ".txt"));
    ...
}

然后使用List类型的静态字段来保存所有数据:

static List<List<Integer>> years = new ArrayList<List<Integer>>();

在阅读方法的底部:

years.add(teams);