gpt4 book ai didi

java - 尝试查找数组平均值时数组大小不正确,如何解决此问题?

转载 作者:行者123 更新时间:2023-12-01 19:51:06 25 4
gpt4 key购买 nike

在我的类(class)中,我有多个科目,每个科目可以有很多作业。我试图找到“taskingGradeAchieved”不为空的每项作业的平均成绩。

在一个数组中,我存储了这些 assignmentGradeAchieved。我想找到平均结果(将每个数字加在一起然后除以项目数)但是它没有显示正确的数组大小。当它应该是 2 时却显示为 1。这是我尝试查找数组大小的代码行: arraySize = (assignmentGradesAchieved.size());

//对于属于主题的每个作业,如果AssignmentGradeAchieved 不为null,则将AssignmentGradeAchieved 添加到名为AssignmentGradesAchieved 的数组列表中。//如果一个科目有多个具有AssignmentGradeAchieved 的作业,则应将多个AssignmentGradeAchieved 添加到名为AssignmentGradesAchieved 的arryalist 中。因此数组的大小应该大于一。//我的一个科目有两项作业,两者的成绩均为AssignmentGradeAchieved,因此数组大小应为2而不是1

    for(int i=0; i<subjects.size(); i++){ //for each subject in the list
Subject subject = subjects.get(i);


List<Assignment> assignments = subject.getAssignment(); //Get the list of assignments belonging to current subject

for(int y=0; y<assignments.size(); y++ ) { //For each assignment in the list
Assignment assignment = assignments.get(y);

ArrayList<Double> assignmentGradesAchieved = new ArrayList<Double>();
if(assignments.get(y).getAssignmentGradeAchieved()!=null) {
assignmentGradesAchieved.add(assignments.get(y).getAssignmentGradeAchieved());
arraySize = 0;
arraySize = (assignmentGradesAchieved.size());
for(int z=0; z<assignmentGradesAchieved.size(); z++) {
arraySize = 0;
allAssignments = allAssignments + assignmentGradesAchieved.get(z);

arraySize = (assignmentGradesAchieved.size());
averageAssignGrade = (allAssignments / arraySize);

}
}
}


}

解决方案:

   for(int i=0; i<subjects.size(); i++){ //for each subject in the list
Subject subject = subjects.get(i);

List<Assignment> assignments = subject.getAssignment(); //Get the list of assignments belonging to current subject
ArrayList<Double> assignmentGradesAchieved = new ArrayList<Double>();

for(int y=0; y<assignments.size(); y++ ) { //For each assignment in the list
Assignment assignment = assignments.get(y);
allAssignments =0;

if(assignments.get(y).getAssignmentGradeAchieved()!=null) {
assignmentGradesAchieved.add(assignments.get(y).getAssignmentGradeAchieved());

for(int z=0; z<assignmentGradesAchieved.size(); z++) {

allAssignments = allAssignments + assignmentGradesAchieved.get(z);
}
}

}
arraySize = 0;
arraySize = (assignmentGradesAchieved.size());
averageAssignGrade = (allAssignments / arraySize);


}

最佳答案

您的 assignmentGradesAchieved 声明位于 for 循环内,因此它总是会被重置,因此您的变量将始终只有一个作业等级。将您的声明置于循环之外

关于java - 尝试查找数组平均值时数组大小不正确,如何解决此问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51313624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com