2017-08-04 81 views
1

我正在嘗試創建一個打印出Student細節的類,並且希望知道如何使用intarray並計算其所有標記的平均值。如何使用類方法計算陣列中所有值的平均值

這是我到目前爲止有:

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(); 
} 

}

回答

2

不能使用運營商陣列,從而​​不正確。您需要對所有數組項進行求和並將其存儲在單獨的變量中,然後將其除以5(數組長度)。您可能需要注意空或空數組。

double sum = 0d; 
for(int item : marks) { 
    sum += item; 
} 
return sum/marks.length; 

而且下面的數組的語句打印字符串表示,而不是它的內容。

System.out.println("Student mark: "+marks+"\n"); 

您可以使用下面的方法來打印陣列,

System.out.println("Student mark: "+ Arrays.toString(marks) +"\n"); 
+0

我在Youtube上觀看了關於如何總結數組中所有值的一些vid,但是如何將總和的總和傳遞到「int average()」方法中,而不在「括號內」添加「int sum」? – KWMuller

+1

是的,我剛剛有一個荷馬時刻(德哦)。這在我的Java書中已經解釋過了,但它完全放棄了我的想法。謝謝。 – KWMuller

1

與Java 8:

Arrays.stream(marks).average().getAsDouble(); 

而且你可以轉換爲int(四捨五入)與(int)

(int)Arrays.stream(marks).average().getAsDouble(); 
+0

AFAIK鑄造什麼也沒有圓,它只是在小數點分隔符後切斷每個數字 - 哪個**發生**在數值上等於舍入...但這兩種方法並不是相同的算法,特別是不適用於浮點數......它就像是說水和咖啡是相同的流體,因爲它們都含有/由H2O製成並具有非常相似的性質 – specializt

0
import java.util.stream.*; 

它在包java.util.stream

實施例:

int[] marks = {10,20,30,40,50}; 
int sum = IntStream.of(marks).sum(); 
System.out.println("The sum is " + sum); 
+1

爲什麼不使用[平均()](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#average--)? – specializt

0

由於int[]是一個對象,幷包含與標記的陣列中,操作者/沒有爲這種類型的定義。您將有標記的總和除以他們的號碼,找出平均:

double average() { 
    double markSum = 0; 
    double average; 
    int i; 
    for (i = 0; i < marks.length; i++) { 
     markSum = markSum + marks[i]; 
    } 
    average = markSum/marks.length; 
    return average; 
} 

另外,請注意這裏使用,通常正確的數據類型爲double,因爲int可能讓你不正確(四捨五入)的結果:如果marks = [1, 2, 3, 4]的平均值爲2.5,但通過使用int average(),您將獲得2