将数据文件中的整数插入整数数组时,添加方法不起作用

Add method not working when inserting integers from a data file into an integer array

    import java.util.*;
import java.io.*;
import java.util.Set;
public class tester
{
    public static void main(String args[]) throws Exception
    {
        BufferedReader reader1 = new BufferedReader(new FileReader("numbers1.in"));
        //this will create a buffered reader to read the file, read each line
        //and count how many lines there are so I can easily create my array
        int lines = 0;
        while (reader1.readLine() != null)//reads each line
        {
            lines++;
        }
        reader1.close();


        Scanner reader2 = new Scanner(new File("numbers1.in"));//new scanner to read the file
        int numbers[] = new int[lines];//creates my array with correct array dimensions
        while(reader2.hasNextLine())
        {
            int next = reader2.nextInt();
            numbers.add(next);
        }



    }
}

我是这方面的初学者,请原谅乱七八糟的代码。我正在尝试从包含整数列表的数据文件中读取整数,每个整数由一个新行分隔。我必须将它们中的每一个添加到一个整数数组中,由于某种原因,来自 java.util.Set 的 .add 方法不起作用,给我一条错误消息,指出找不到添加方法。

非常感谢任何帮助,谢谢!

在 java array 中长度是不可变的。它没有 add 方法。

使用 List

List<int> numbers = new ArrayList<>();

while(reader2.hasNextLine()) {
     int next = reader2.nextInt();
     numbers.add(next);
}

或者,如果您只需要使用数组

int index = 0;

while(reader2.hasNextLine()) {
         int next = reader2.nextInt();
         numbers[index++] = next;
    }