[英]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. 我正在尝试从2D数组的每一行中添加int,然后找出总计最高的行。 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. 您可以声明一个变量,例如int maxScore。 Then inside the first for loop you set it equal to 0 to clear it for each player.
然后在第一个for循环内将其设置为0,以清除每个玩家。 In the second for loop you can then do
在第二个for循环中,您可以执行以下操作
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. 这将为您提供每个玩家的maxScore。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.