繁体   English   中英

用Java添加2D数组行

[英]adding 2D array rows with Java

我正在尝试从2D数组的每一行中添加int,然后找出总计最高的行。 数组的大小是可变的,由用户在程序开始时声明。

// 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();
    } 
}

现在我希望找到每位球员(行)的最高成绩。 我不确定是否应该使用一种方法。 或者我应该使用哪种方法。 我稍微了解如何从数组中添加内容,但是我不了解如何在每次运行程序时从数量不同的行中添加内容。

您可以声明一个变量,例如int maxScore。 然后在第一个for循环内将其设置为0,以清除每个玩家。 在第二个for循环中,您可以执行以下操作

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

这将为您提供每个玩家的maxScore。 然后,您可以存储该变量或将其打印出来。

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);
}

暂无
暂无

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

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