简体   繁体   中英

adding 2D array rows with Java

I am trying to add the int's from each row of a 2D array and then find which row has highest total. The size of the array is variable, being declared by the user at the beginning of the program.

// a 2D Array named score is made. Its axis' are maxComp and maxRound       

int[][] score = new int[maxComp][maxRound];

//Player x is called

for (int x = 0; x < maxComp; x++) {
    System.out.println("Player " + (x+1));
    //Player x enters all their scores
    for (int r = 0; r < maxRound; r++) {
        System.out.println("Enter your score for round " + (r + 1) );
        score [x][r] = in.nextInt();
    } 
}

now i wish to find the highest score form each player (row). I'm not sure if I should be using a method. Or which method I should use. I slightly understand how to add things from an array, but I don't understand how to add from rows that vary in number each time the program is run.

You can declare a variable such as int maxScore. Then inside the first for loop you set it equal to 0 to clear it for each player. In the second for loop you can then do

if(r == 0)
    maxScore = score[x][r]
else if(maxScore < score[x][r])
    maxScore = score[x][r]

This will give you the maxScore for each player. Then you can either store that variable or print it out.

for (int x = 0; x < maxComp; x++) {
    int maxScore = 0;
    for (int r = 0; r < maxRound; r++) {
        int currentScore = score [x][r];
        if(currentScore > maxScore){
            maxScore = currentScore;
        }
    }
    System.out.println("Player " + x + " max Score is " + maxScore);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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