Read file contents into an ArrayList

后端 未结 2 742
有刺的猬
有刺的猬 2021-01-23 07:09

On a previous project I was required to read file contents into an array. Now I have to do the same thing only I have to read the contents into an ArrayList. A few problems I

相关标签:
2条回答
  • 2021-01-23 07:13

    Instead of assigning the line to array[i], simply do arrayList.add(line)

    If this is not homework, consider using some 3rd party utilities like apache-commons FileUtils.readLines(..) or guava Files.readLines(..)

    0 讨论(0)
  • 2021-01-23 07:37

    The if condition will always be false:

    for (int i = 0; i < 10; i++) {
        if(i > 10) {
            System.out.println("The file you are accessing contains more than 10      input values.  Please edit the file you wish to use so that it contains"
                            + "> 10 input values.  The program will now exit.");
                    System.exit(0);
        }
    

    To append to an ArrayList use its add() method. ArrayList has a method size() which you could use to determine if the file contained more than ten inputs.

    EDIT:

    The terminating condition of your for loop should be based on numbers.length, and not ten.

    0 讨论(0)
提交回复
热议问题