【发布时间】:2017-08-04 13:25:46
【问题描述】:
我正在尝试创建一个打印出Student 详细信息的类,我想知道如何获取int array 并计算他们所有分数的平均值。
这是我目前所拥有的:
public class Student {
private int id;
private String name;
private String course;
private int[] marks;
Student (int id, String name, String course, int [] marks) {
// constructor which creates a student according to the specified parameters
this.id = id;
this.name = name;
this.course = course;
this.marks = marks;
}
int average () {
// calculates and returns the average mark for the student
return marks / 5; // error: the operator / is undefined for the argument type int[]
}
void print () {
// prints student details
System.out.println("Student ID: "+id+"\n");
System.out.println("Student Name: "+name+"\n");
System.out.println("Course enrolled on: "+course+"\n");
System.out.println("Student mark: "+marks+"\n"); // This prints a hashcode for some reason
}
}
具体来说,我的问题是如何在“int average()”方法中返回int[] 标记的平均值(不更改括号中的标头或参数)?
public class T3Main {
public static void main(String[] args) {
Student s1 = new Student(1234, "Joe Bloggs", "Computer Studies", new int[] {67, 55, 78, 72, 50});
Student s2 = new Student(2341, "Sue White", "Computer Science", new int[] {57, 85, 58, 49, 61});
Student s3 = new Student(3412, "Ben Black", "Software Engineering", new int[] {71, 45, 66, 70, 51});
s1.print();
s2.print();
s3.print();
}
}
【问题讨论】: