3 回答
TA贡献1775条经验 获得超8个赞
您可以添加一个比数组多一个空间的结果数组unitcode,并将值分配给它,而不是修改输入:
public String[] unitMarks(int[] grades, String[] unitCode) {
double sum = 0;
for (double i : grades) {
sum += i;
}
double average = (sum / grades.length);
String[] result = new String[grades.length +1];
for (int i = 0; i < grades.length; i++) {
String combination = unitCode[i] + grades[i];
result[i] = combination;
}
result[result.length-1]= "Average:"+average;
return result;
}
TA贡献1874条经验 获得超12个赞
有两种方法可以做到这一点。1. 使用ArrayList,当向其中添加元素时,它的大小会增加
public List<String> unitMarks(int[] grades, String[] unitCode)
{
List<String> unitCodeArrayList = new ArrayList<String>();
double sum = 0;
for (double i : grades)
sum += i;
double average = (sum/grades.length);
for (int i = 0; i <grades.length; i++)
{
String combination = unitCode[i]+grades[i];
unitCodeArrayList.add(combination);
}
unitCodeArrayList.add("Average:"+average);
return unitCodeArrayList;
}
使用原始数组,但以这种方式附加到它(因为我不确定它的大小是多少)
public String[] unitMarks(int[] grades, String[] unitCode)
{
double sum = 0;
for (double i : grades)
sum += i;
double average = (sum/grades.length);
for (int i = 0; i <grades.length; i++)
{
String combination = unitCode[i]+grades[i];
unitCode[i] = combination;
}
String[] resUnitCode = appendArray(unitCode, "Average:"+average);
return resUnitCode;
}
private String[] appendArray(String[] array, String x){
String[] result = new String[array.length + 1];
for(int i = 0; i < array.length; i++)
result[i] = array[i];
result[result.length - 1] = x;
return result;
}
TA贡献1735条经验 获得超5个赞
如果只需要显示数值,可以使用 Stream 计算平均值并一次性显示:
private void displayGradesAndAverage(int[] grades, String[] unitCode) {
IntStream.range(0, grades.length)
.peek(i -> System.out.print(unitCode[i] + grades[i] + ", "))
.map(i -> grades[i])
.average()
.ifPresent(avg -> System.out.println("Average:" + avg));
}
添加回答
举报