2011-10-30 60 views
1

我知道在論壇中有很多像這樣的問題,但在搜索了一段時間後,我還沒有找到答案。我對編程也很陌生,所以請不要激怒我。初始數組對象和傳遞值

我想創建我的課程8個對象,並將不同的值傳遞給他們。

f.e.

public class exampleClass(){ 
int value; 
} 

,然後初始化它們:

for(int i=0; i<7; i++){ 
exampleClass c= new // I get lost at this point 
        //and how can we pass "i" to the var "value" inside the new objects? 
} 

非常感謝!

回答

3

您需要給ExampleClass一個構造函數來填充值。例如:

public class ExampleClass { 
    private final int counter; 

    public ExampleClass(int counter) { 
     this.counter = counter; 
    } 
} 

... 

ExampleClass[] array = new ExampleClass[7]; 
for (int i = 0; i < array.length; i++) { 
    array[i] = new ExampleClass(i); 
} 
+0

+1:這是一個恥辱,你不能投兩次。 ;) –

+0

+1完美。非常感謝Jon! – menemenemu