2011-06-29 20 views
0

我正在處理兩個帶有字符串數組的字符串(字符串只是句子),並將它們分配給保存在另一個數組中的類(下面顯示的Sentence類數組碼)。正在用循環中的最後一個索引覆蓋的數組

所以這是我的問題。當調用popList()時,for循環會遍歷兩次並正常工作,將addStrings和addTranslation的第一個索引放入數組的第一個類中。但是,當循環索引並再次運行temp.sentence = addStrings [1]時,它也會覆蓋第一個類的.sentence。然後,當temp.translations = addTranslations [1]再次運行時,它會覆蓋第一個類的翻譯。

因此,在循環結束時,所有數組都被填充相同的東西:addStrings和addTranslation的最後一個索引。每次它循環覆蓋所有索引之前,它應該與它應該投入索引。

任何人都知道這是什麼問題?謝謝!

public class Sentence { 
public String sentence; 
public String translation; 
Sentence() { 
    sentence = " "; 
    translation = " "; 
} 
} 

    private void popStrings() { 
    addStrings[0] = "我是你的朋友。"; addTranslations[0] = "I am your friend."; 
    addStrings[1] = "你可以幫助我嗎?"; addTranslations[1] = "Could you help me?"; 
    addStrings[2] = "我不想吃啊!"; addTranslations[2] = "I don't want to eat!"; 
} 
//Fill Sentence array with string and translation arrays 
private void popList() { 
    int i = 0; 
    Sentence temp = new Sentence(); 
    for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) { 
     temp.sentence = addStrings[i]; 
     temp.translation = addTranslations[i]; 
     sentences[i] = temp; 
    } 
} 

回答

1

您需要創建新的句子()內循環:

for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) { 
    Sentence temp = new Sentence(); 
    temp.sentence = addStrings[i]; 
    temp.translation = addTranslations[i]; 
    sentences[i] = temp; 
} 

否則,你在同一個對象不斷設置句子和翻譯。

+0

這對我來說很奇怪,我認爲所有事情都被索引,臨時值正在改變......仍然沒有看到它在它之前如何影響指數。無論如何,感謝它現在的作品。 – lespommes

+0

temp沒有編入索引....通過編寫temp.sentence = xxxx您說過 - 請將對象temp中的句子設置爲xxx。然後你將句子[i]設置爲temp。在java對象中是引用,所以實際上句子中的所有元素都引用同一個對象(temp)。 –

+0

謝謝,現在有道理 – lespommes

相關問題