ArrayList在do..while循环中没有按预期工作

时间:2013-04-25 14:52:37

标签: java string arraylist do-while

我有以下循环创建一个完全适合屏幕的字符串,它可以创建一个页面。

    for (int i = 0; i < totalLine; i++) {

        temp = enterLine(mTextView, textToBeShown, i);
            full = full + temp;

    }

因此,迭代完成后full会保留一页。

我想要做的是创建一个外部迭代,它允许我创建多个页面,不会定义要创建的页面数量。因此,如果没有更多页面要创建,迭代需要停止。

我尝试了以下代码,但出于某种原因,在调用页面Pages.get(1)时,它会发出整个字符串,而不仅仅是full / Page。例如,如果我在ArrayList 页面中添加了三个字符串,则ArrayList中会有三个字符串,但所有字符串都具有相同的值。

使用Log进行一些测试,我知道第一次迭代运行良好,而full给出了预期的值,这意味着在第一次do迭代中给出了期望的值到full所以第二次迭代等等。

    do{
    for (int i = 0; i < totalLine; i++) {

        temp = enterLine(mTextView, textToBeShown, i);
        if(temp.trim().length() == 0){
            break;
        }else{
            full = full + temp;
        }
    }
    Pages.add(full);

所以问题是我在ArrayList做错了什么,以及为什么它没有像我期待的那样工作。

修改

这是enterLine代码:使用了更多Log,并没有感觉需要全部显示。

public String enterLine(TextView mTextView, String textBeShown, int i){

        String A;
        int number = mTextView.getPaint().breakText(textToBeShown, 0, textToBeShown.length(),true,mTextView.getWidth(), null);

        if(textToBeShown.substring(number-1,number) != " "){
            number = textToBeShown.substring(0,number).lastIndexOf(" ");
            Log.e("TAG1", "Found " + i);
        }

        A = (textToBeShown.substring(0, number) + "\n");
        Log.e(TAG, textToBeShown.substring(0, number));
        textToBeShown = textToBeShown.substring(number, textToBeShown.length());
        return A;
    }

2 个答案:

答案 0 :(得分:1)

从它的外观来看,它不是你的arraylist而是你的循环。 Add向arraylist添加一个元素,get(index)从列表中获取index'th元素。没问题。

你的问题是它在循环之后向页面添加了完整的内容,此时full已经包含了所有内容。将pages.add放在循环中,它将被修复。确保每次迭代都重置完整。在循环开始时输入full =“”。应该工作。

答案 1 :(得分:1)

do{
    full=""
    for (int i = 0; i < totalLine; i++) {
        temp = enterLine(mTextView, textToBeShown, i);
        if(temp.trim().length() == 0){
            break;
        }else{
            full = full + temp;
        }
    }
    Pages.add(full);
}while(...)

或更好

do{
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < totalLine; i++) {
        temp = enterLine(mTextView, textToBeShown, i));
        if(temp.trim().length() == 0){
            break;
        }else{
            builder.append(temp);
        }
    }
    Pages.add(builder.toString());
}while(...)
相关问题