开发者

Array Being Overwritten with Last Index in Loop

I'm working on code that takes two arrays with strings (the strings are just sentences) and allocates them to classes which are held in another array (The Sentence class array shown below in the code).

So here's my problem. When popList() is called, the for loop runs through twice and works fine, putting the first index of addStrings and addTranslation into the first class in the array. However, when the loop indexes up and runs temp.sentence = addStrings[1] again, it OVERRIDES t开发者_如何转开发he first class's .sentence also. Then when temp.translations = addTranslations[1] runs again it OVERRIDES the first class's .translation.

So by the end of the loop, all of the arrays are filled with the same thing: the last index of addStrings and addTranslation. Every time it loops it overwrites all the indices before it with the index it's supposed to be putting in.

Anyone know what the problem is here? Thanks!

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


You need to create new Sentence() inside the loop:

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

Otherwise you set sentence and translation continuously in the same object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜