java如何将2D字符串数组的结果除以子数组的长度?
如何将2D数组的结果除以子数组的长度。我需要第三个问题的帮助。Where是要求输入缺失的代码行以查找每个跑步者的平均时间。使用平均值
这里有一个问题:“我们给了你一个名为averageVal的变量,它当前存储0。编辑这行代码以找到每个跑步者的平均时间。”
public class RowMajor {
public static void main(String[] args) {
// Given runner lap data
double[][] times = {{64.791, 75.972, 68.950, 79.039, 73.006, 74.157}, {67.768, 69.334, 70.450, 67.667, 75.686, 76.298}, {72.653, 77.649, 74.245, 62.121, 63.379, 79.354}};
// Replace the incorrect for loop headers, use the iterators 'outer' and 'inner' for the outer and inner loops
double runnerTime = 0.0;
for(int outer = 0; outer < times.length; outer++) {
runnerTime = 0.0;
for(int inner = 0; inner < times[outer].length; inner++) {
System.out.println("Runner index: " + outer + ", Time index: " + inner);
// Enter the missing line of code to sum up the values in each row. Use the variable runnerTime
runnerTime += times[outer][inner];
}
// I need help with this question below.
// Enter the missing line of code to find the average time of each runner. Use the variable averageVal
double averageVal = 0;
// Below is what I tried but it keep showing an error "The correct average time for runner 0 was not printed to the console."
double averageTime = runnerTime / times[outer].length;
System.out.println("Sum of runner " + outer + " times: " + runnerTime + averageTime);
System.out.println("Average of runner " + outer + ": " + averageVal + averageTime);
}
}
}
# 1 楼答案
我想这条线已经成功了
问题是当你用
averageVal
和averageTime
没有加在一起(我不明白你为什么要加它们)。它们附在后面例如
输出是13,而不是4
原因是,当您在字符串中同时打印一个原语时,原语将是auto boxed到整数,语句将变成
"".toString() + one.toString() + three.toString()
。因为toString()
返回字符串,所以运算符+
将直接链接它们我整理了你的代码,并在下面发布了输出
控制台输出