问题
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