2015-03-13 115 views
-1

好的,我正在做一個練習,我有一個包含3個測試分數的對象。帶參數的Setter函數

然後,我有一個設置函數,它需要2個參數,測試編號和您設置的分數。

現在我的問題是,我不知道如何使測試編號參數正常工作。

該代碼的作品,如果我做test1 = score,但是當我把student1.test1置於set參數,出於某種原因它不會註冊。

我希望你能指點我正確的方向,我會很感激!

我有一個主類和學生類:

public class Main { 
    public static void main(String[] args) { 
     Student student1 = new Student(); 
     student1.setTestScore(student1.test1, 50); 
     System.out.print(student1.test1); 
    } 
} 

public class Student { 
    int test1; 
    int test2 = 0; 
    int test3; 

    Student() { 
     int test1 = 0; 
     int test2 = 0; 
     int test3 = 0;  
    } 

    public void setTestScore(int testNumber, int score){ 
     testNumber = score; 
    } 
} 
+0

你會好很多推遲作出'test'獨立類。 – Andrew 2015-03-13 14:06:00

+0

我建議你在私人學生類和你的構造函數中創建整數,然後重新聲明你的變量。 – 2015-03-13 14:06:36

+1

基本想法是錯誤的。你不會像那樣改變價值。 – HuStmpHrrr 2015-03-13 14:08:42

回答

3

Java是按值傳遞的語言,所以當你通過student1.test1student1.setTestScore,你是路過該成員的副本。你沒有傳遞給成員的引用。因此該方法不能更改成員的值。

即使語言允許進行這種修改,但在面向對象的編程方面,這將是一個壞主意,因爲您通常會將成員設置爲私有的,並且不會直接從課程外部訪問它們。

另一種可能是使用數組:

public class Student { 
    int[] test = new int[3]; 
    ... 

    public void setTestScore(int testNumber, int score){ 
     if (testNumber >= 0 && testNumber < test.length) 
      test[testNumber]=score; 
    } 
    ... 
} 

,你會打電話像這樣的方法:

student1.setTestScore(0, 50); // note that valid test numbers would be 0,1 and 2 
+0

@BoristheSpider是的,我剛剛添加了一個例子來說明這一點。 – Eran 2015-03-13 14:11:40

+0

在這種情況下,傳遞值聲明是否重要?因爲傳遞給方法的值是原始的而不是對對象的引用? – CKing 2015-03-13 14:13:30

+0

@bot其他語言,如C和C++,允許傳遞任何變量的引用,所以我假設這是OP的錯誤的原因 – Eran 2015-03-13 14:15:42