简体   繁体   English

在java中从两个不同的季度添加数组总数

[英]Adding the array totals from two separate quarters in java

I am working on a project to allow users to input values for two separate teams for a two-quarter game.我正在开展一个项目,允许用户为两个独立的团队输入两节比赛的值。 The project should ask users to select which team scored and then how many points they got.该项目应要求用户选择得分的团队以及他们获得的分数。 Then, it would total the points for each of the individual teams for the quarter.然后,它将合计每个团队在本季度的积分。 Finally, it should add each team's points for the two quarters together.最后,它应该将两个季度的每个团队的积分相加。 Currently, I'm able to get the individual teams score for each quarter but, I am not sure how to add the points for each quarter together.目前,我能够获得每个季度的各个团队的分数,但我不确定如何将每个季度的分数加在一起。

public class goingUp {
static int team1[] = new int[4];
static int team2[] = new int[4];
static int teamOneScore = 0;
static int teamTwoScore = 0;            
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) { for (int Quarter = 1; Quarter <= 2; Quarter++) {
        System.out.println("Quarter " + Quarter +"\n");
        for (int i = 0; i < 4; i++) {
            System.out.println("What team scored?(1 or 2)");
            int iTeam = keyboard.nextInt();

            System.out.println("How many points did they score (1,2, or 3)");
            int pointsScored = keyboard.nextInt();
            if (iTeam == 1) {
                teamOneScore += pointsScored;
            } else if (iTeam == 2) {
                teamTwoScore += pointsScored;
            }
        }
        System.out.println("Team 1 score is " + teamOneScore);
        System.out.println("Team 2 score is " + teamTwoScore);

        for (int i = 0; i < team1.length; i++) {

            team1 = new int[]{teamOneScore};
        }
    }
    System.out.println("Team one score for all Quarters is " + teamTotal(team1));
}

static int teamTotal(int team[]){

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

} }

You could iterate over both arrays and sum the corresponding elements:您可以遍历两个数组并对相应的元素求和:

int[] bothTeamsScore = new int[4];
for (int i = 0; i < 4; ++i) {
    bothTeamsScore[i] = teamOneScore[i] + teamTwoScore[i];
}

EDIT:编辑:
Based on the comment below, I misunderstood the question.根据下面的评论,我误解了这个问题。 To sum each team's score, you could iterate over the array and sum it要对每个团队的得分求和,您可以遍历数组并将其求和

private static long sum(int[] scores) {
    long sum = 0L;
    for (int i = 0; i < scores.length; ++i) {
        sum += scores[i];
    }
    return sum;
}

long teamOneTotal = sum(teamOneScore);
long teamTwoTotal = sum(teamTwoScore);

Alternatively, streams can make this method a tad simpler:或者,流可以使这个方法更简单一点:

private static long sum(int[] scores) {
    return Arrays.stream(scores).sum();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM