我正在编写一个保龄球分数计划,我输入一系列保龄球的昵称,然后制作一个平行的2D数组,分数为4轮。然后在最后我应该能够打印他们的分数和他们的分数的平均值。但是,我对平均值的代码循环遍历每个数字并将其除以4。每次它也将数字添加到前一个数字。 toString方法也不起作用。
import java.util.Arrays;
public class BowlingScores {
public void printScores()
{
String[] nicknames = {"Kylie", "Caitlyn", "Kim", "Kanye"};
int[][] scores =
{{145, 167, 183, 193},
{76, 84, 92, 104},
{77, 177, 182, 196},
{300, 300, 300, 300}};
int sum = 0;
for(int index = 0; index < scores.length; index++)
for(int j = 0; j < 4; j++)
{
sum = sum + scores[index][j];
int average = sum/ scores.length;
System.out.println("");
System.out.print(nicknames[index] + " bowled rounds of " + scores[index] + " and had an average of " + average);
}
}
}
答案 0 :(得分:0)
这应解决您的聚合问题和toString()
问题:
for (int index = 0; index < scores.length; index++) {
int sum = 0;
for (int j = 0; j < scores[index].length; j++) {
sum = sum + scores[index][j];
}
int average = sum / scores[index].length;
System.out.println(nicknames[index] + " bowled rounds of "
+ Arrays.toString(scores[index])
+ " and had an average of " + average);
}
请注意,数组上的toString()
直接无法正常工作。相反,您应该使用明确的java.util.Arrays.toString()
。