有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当我必须使用文件读取器Java时,如何从txt文件填充数组??

我必须用文本文件中的整数填充一个数组,我需要文件读取器从每一行中提取一个整数并放入一个数组,但它不能将重复项放入数组,这使得数组更加复杂,而重复项,我必须将它们写入另一个文本文件,例如:排序。txt,我不知道该怎么做,我只是在我上大学的第一年。如果有人能帮忙,我们将不胜感激。提前谢谢

以下是我在我的方法中得到的结果

public static void readFromfile()throws IOException {
    List<String> lines = new ArrayList<String>();
    BufferedReader reader = null;
    try {
     reader = new BufferedReader(new FileReader("file.txt"));
     String line = null;
     while ((line = reader.readLine()) != null) {
        lines.add(line);
    }
} finally {
    reader.close();
}
int[] array = lines.toArray();// i keep getting incopatible type error in this line
awell

在过去的6天里,我一直在做这件事,这就是我取得的成绩:(


共 (4) 个答案

  1. # 1 楼答案

    你的问题是你有一个List of Strings,你试图把它变成一个int array

    正如T.J.Crowder指出的,但是不能有List<int>——必须使用包装类Integer

    因此,将列表更改为List<Integer>,然后它将是lines.add(Integer.parseInt(line));

  2. # 2 楼答案

    我建议使用Scanner类,它比你正在做的更简单。 错误是由于将对象指定给整数类型

  3. # 3 楼答案

    使用Scanner类将使事情变得更简单

    List<Integer> numbers = new ArrayList<Integer>();
    Scanner s = new Scanner(new FileInputStream("file.txt"));
    
    while (s.hasNextInt()) {
       numbers.add(s.nextInt());
    }
    
  4. # 4 楼答案

    int[] array = lines.toArray();// i keep getting incopatible type error in this line
    

    当然可以,List<String>#toArray返回一个Object[],而不是一个int[].:-)

    理想情况下,您可以通过将列表声明为List<int>(或者List<long>,如果数字非常大的话)。不幸的是,至少在Java6中,您不能这样做,必须使用List<Integer>/List<Long>。这就是你的出发点

    然后,边走边解析字符串中的数字(例如,来自^{^{}(或^{})可以为您进行解析。它们的结果分别是intlong,但是当它们被添加到列表中时,它们会自动装箱

    或者,您可以查看^{} class,它是“…一个简单的文本扫描程序,可以使用正则表达式解析原语类型和字符串…”

    例如,从List<Integer>列表中获取int[]的最终数组有点麻烦。如果您可以使用Integer[](而且由于自动装箱/取消装箱,您基本上可以这样做),这很容易:Integer[] numbers = yourList.toArray(new Integer[yourList.size()]);

    如果你真的需要一个int[],你必须写一个循环来复制它,或者使用类似Apache Commons ^{} method的东西