How to populate an array list in a while loop

空扰寡人 提交于 2019-12-13 09:27:04

问题


My problem is this

Scanner sf = new Scanner(f);
ArrayList<String> teamArr = new ArrayList<String>();
int counterPopulate = 0;

while(sf.hasNextLine()){
    teamArr[counterPopulate] = sf.nextLine();
    counterPopulate++;           
}

Any solutions, this is surrounded by a try catch. Getting the problem at this part teamArr[counterPopulate] = sf.nextLine();


回答1:


Because ArrayList is different than normal arrays, you need to use methods of the ArrayList class to populate the ArrayList.

In your case you need to do:

while(sf.hasNextLine()){
            teamArr.add(sf.nextLine());
        }

Assuming you're using Java.

Have a look at http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html




回答2:


As you are using ArrayList<String>, add(String value) method is used to add new String Object into the ArrayList.

A simple solution of your problem is given below.

assuming that language is JAVA.

Scanner sf = new Scanner(f);
ArrayList<String> teamArr = new ArrayList<String>();

while( sf.hasNextLine() ) {
    teamArr.add(sf.nextLine());
}

for more details about ArrayList and Collection please refer :

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html



来源:https://stackoverflow.com/questions/19568485/how-to-populate-an-array-list-in-a-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!