【问题标题】:How to populate an array list in a while loop如何在while循环中填充数组列表
【发布时间】:2013-11-03 07:28:01
【问题描述】:

我的问题是这个

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

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

任何解决方案,这都被 try catch 包围。 在这部分遇到问题teamArr[counterPopulate] = sf.nextLine();

【问题讨论】:

  • 这是什么语言?
  • 因为String是大写的,所以看起来像java
  • 您是否收到index out of bounds 异常?如果没有,你得到了什么例外
  • @SamIam 我什至不认为您可以按照他尝试添加到 ArrayList 的方式运行代码
  • 建议未来的问题:如果有错误信息,请提供。在这个例子中,这对于专业人士来说有点明显,但这些信息可以更轻松地帮助您解决更复杂的问题

标签: java arraylist while-loop


【解决方案1】:

由于ArrayList与普通arrays不同,需要使用ArrayList类的方法来填充ArrayList

在您的情况下,您需要这样做:

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

假设您使用的是 Java。

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

【讨论】:

    【解决方案2】:

    当您使用ArrayList&lt;String&gt;时,add(String value)方法用于将新的String对象添加到ArrayList中。

    下面给出了您的问题的简单解决方案。

    假设语言是 JAVA。

    Scanner sf = new Scanner(f);
    ArrayList<String> teamArr = new ArrayList<String>();
    
    while( sf.hasNextLine() ) {
        teamArr.add(sf.nextLine());
    }
    

    更多关于ArrayListCollection的详情请参考:

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

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

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 2015-04-30
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多