2014-01-17 60 views
0

我想用Person類型的對象填充數組。 (Person包含字符串姓氏和名字,ID爲典型整數)簡單對象失敗的數組

填充數組後,生病嘗試打印整個數組。但它總是打印我輸入「x」次的最後一個名字......我嘗試使用包含整數的數組的相同方法,並且它可以工作。 也許你們中的一些人有什麼線索出現​​錯誤?

下面是代碼snipplet:

public class Tester { 

public static void Test() { 
    int i=0, counter = 0, idx = 0; 

    Person[] TestArray = new Person[3]; 
    Person testperson = new Person(); 
    testperson.lastname = ""; 
    testperson.firstname = ""; 
    testperson.id = 0; 
    TestArray[0] = testperson; 
    TestArray[1] = testperson; 
    TestArray[2] = testperson; 

    for (i = 0 ; i < TestArray.length; i++) {  
     //TestArray[i] = testperson; 
     TextIO.put("Enter name: "); 
    TestArray[i].lastname = TextIO.getln(); 
    } 

    TextIO.put("Array contains: \n"); 

    for (i = 0 ; i < TestArray.length; i++) { 
     TextIO.putf("%s ", TestArray[i].lastname);  
    } 

... ... ...

和輸出的樣子:

輸入姓名:姓

輸入名稱:第二個名稱

輸入名稱:thirdname

陣列包含: thirdname thirdname thirdname 發現:

感謝您的幫助!

回答

1

這是因爲數組指向單個對象。你需要爲每個新人做一個new Person()

現在,TestArray[0]TestArray[1]TestArray[2]都是相等的。所以如果你改變其中的一個,它會改變所有其他的(所以爲什麼只顯示最後輸入的名字)。

+0

是的! * facepalm *感謝您的及時答覆! – user3179570

2

也許健忘

Person testperson 

總是引用三次相同的實例。 每次更改同一個對象時。

考慮下面的代碼

Person testperson = new Person(); 
testperson.lastname = ""; 
testperson.firstname = ""; 
testperson.id = 0; 
TestArray[0] = testperson; 

testperson = new Person(); 
testperson.lastname = ""; 
testperson.firstname = ""; 
testperson.id = 1; 
TestArray[1] = testperson; 

testperson = new Person(); 
testperson.lastname = ""; 
testperson.firstname = ""; 
testperson.id = 2; 
TestArray[2] = testperson; 

或更好地利用構造函數初始化Person。 終於讓我建議使用駝峯書寫符號TestArray是一個變量,但「它似乎是一個類」; testArray應該更好

+0

感謝您的好建議!這指出了問題......謝謝! – user3179570

2

這是因爲所有的數組單元都指向相同的地方。 您需要使用new Person()才能爲每個單元格創建一個新實例。

此外,保持你的構造函數的初始化,而不是手動,除非你需要它。

刪除

Person testperson = new Person(); 
testperson.lastname = ""; 
testperson.firstname = ""; 
testperson.id = 0; 

改變數組賦值爲每個單元創建一個新的實例。

TestArray[0] = new Person(); 
TestArray[1] = new Person(); 
TestArray[2] = new Person(); 

添加到下面的Person構造類:

public Person() 
{ 
    lastname = string.Empty(); 
    firstname = string.Empty(); 
    id = 0; 
} 

而且我會強烈建議您使用命名約定。

+1

(+1) – venergiac

+0

@venergiac,謝謝。 –

+0

謝謝!這個提示真的很有幫助 – user3179570