[英]ArrayList not working as expected in do..while loop
我有以下循環創建一個完全適合屏幕的字符串,可以說創建了一個頁面。
for (int i = 0; i < totalLine; i++) {
temp = enterLine(mTextView, textToBeShown, i);
full = full + temp;
}
因此,在完成迭代后, full
將占據一頁。
我想做的是創建一個外部迭代,該迭代使我可以創建多個頁面,但未定義要創建的頁面數量。 因此,如果沒有更多頁面要創建,則迭代必須停止。
我嘗試了以下代碼,但是由於某些原因,在調用頁面Pages.get(1)
它給出了整個String而不只是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;
}
從外觀上看,它不是您的arraylist,而是您的循環。 Add將一個元素添加到arraylist,get(index)從列表中獲取第index個元素。 沒問題。
您的問題是它在循環后將完整內容添加到頁面中,到此為止,完整內容已包含所有內容。 將pages.add放入循環中,它將得到修復。 確保您在每次迭代時都將其重置為完整狀態。 在循環的開始處放入full =“”。 那應該工作。
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(...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.