我正在嘗試創建一個打印出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[]
標記的平均中的「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();
}
}
我在Youtube上觀看了關於如何總結數組中所有值的一些vid,但是如何將總和的總和傳遞到「int average()」方法中,而不在「括號內」添加「int sum」? – KWMuller
是的,我剛剛有一個荷馬時刻(德哦)。這在我的Java書中已經解釋過了,但它完全放棄了我的想法。謝謝。 – KWMuller