簡體   English   中英

無法訪問的代碼-不應無法訪問

[英]Unreachable Code - Shouldn't be unreachable

我想用從文件中讀取的數據填充自定義列表視圖。 使用方法ReadPeopleDetails讀取文件。 這將返回一個arraylist,然后我使用循環使用名稱字符串並將其放入arraylist people_name中。

但是,顯然是由於for循環, final ArrayAdapter適配器行無法訪問。 第二雙眼睛能告訴我為什么嗎?

我認為for循環將結束(長度由arraylist的長度指定)

碼:

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.add_party__people_list, menu);
    ArrayList<PeopleDetails> people_list = Readpeopledetails();
    ArrayList<String> people_name = null; ///this will catch the names from the above line, and put them into
    ///an arraylist for use in populating the ListView
    int i = people_list.size();
    //int j; acts as counter in iterator system
    PeopleDetails[] people_array = (PeopleDetails[]) people_list.toArray();
    for(int j = people_list.size(); /*not using termination*/ ; j++ ){
        people_name.add(people_array[j].name);

    }

    final ArrayAdapter adapter = new ArrayAdapter(this, R.layout.person_list_item, people_name);
    return true;
}
for(int j = people_list.size(); /*not using termination - SO LOOP WONT END*/ ; j++ ){

這是從列表的末尾開始,然后從那里開始遞增,因此它將永遠持續下去。 你可能想要...

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

沒有結束循環的條件。 所以現在是一個無限循環..所以下一行不可達

做類似的事情

for(int j = 0; j< people_list.size(); j++ ){
        people_name.add(people_array[j].name);

    }

似乎您是Java新手。 要了解有關for循環的更多信息,請參見此處的文檔

除了循環不會終止之外,people_name從未分配給ArrayList,因此當您嘗試在其上調用add方法時,您將獲得NullPointerException。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM