简体   繁体   中英

Unreachable Code - Shouldn't be unreachable

I want to populate a custom listview, with data read from a file. The file is read using method ReadPeopleDetails . This returns an arraylist, which I then, using a loop, take the name string and put it into arraylist people_name.

However apparently the final ArrayAdapter adapter line is unreachable, presumably because of the for loop. Could a second pair of eyes tell me why this is?

I would think the for loop will end (length specified by length of arraylist)

Code:

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++ ){

This is starting at the end of the list and incrementing from there, so it will go on forever. You probably want...

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

there is no condition for ending the loop. so it is a infinite loop now.. so the next line is unreachable

do something like

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

    }

Seems you are new to java. To learn more about for loop see the doc here

除了循环不会终止之外,people_name从未分配给ArrayList,因此当您尝试在其上调用add方法时,您将获得NullPointerException。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM