0

我必须用文本文件中的整数填充一个数组,我需要文件阅读器从每一行获取一个整数并放入一个数组中,但它也不能将重复项放入数组中,这使得它更加复杂,和重复项,我必须将它们写入另一个文本文件,例如:sorted.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

4 回答 4

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

你当然会,List<String>#toArray返回一个Object[],而不是一个int[]。:-)

理想情况下,您可以通过将列表声明为List<int>(或者List<long>如果数字真的很大)来做到这一点。不幸的是,至少在 Java 6 中,你不能这样做,你必须使用List<Integer>/List<Long>来代替。所以这是你的起点。

然后随时解析字符串中的数字(例如, from line)。Integer.parseInt(或Long.parseLong)可以为您进行解析。它们的结果分别是intlong,但是当它们添加到列表中时会自动装箱。

或者,您可能会查看Scanner,它是“......一个简单的文本扫描器,可以使用正则表达式解析原始类型和字符串......”

int[]从列表中获取(例如)的最终数组List<Integer>有点痛苦。如果您可以使用 anInteger[]代替(并且由于自动装箱/拆箱,您大部分都可以),那很容易:Integer[] numbers = yourList.toArray(new Integer[yourList.size()]);

如果你真的需要一个int[]代替,你必须编写一个循环来复制它,或者使用类似Apache Commons的toPrimitive方法

于 2013-05-13T13:35:40.550 回答
0

I recommend to use Scanner class, it is easier than what you are doing. The error is due to assigning object to integer type.

于 2013-05-13T15:06:33.683 回答
0

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

正如 TJ Crowder 指出的那样,但是您不能拥有List<int>- 您必须使用 wrapper class Integer

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

于 2013-05-13T13:42:43.007 回答
0

使用 Scanner 类将使事情变得更容易。

List<Integer> numbers = new ArrayList<Integer>();
Scanner s = new Scanner(new FileInputStream("file.txt"));

while (s.hasNextInt()) {
   numbers.add(s.nextInt());
}
于 2013-05-13T13:38:43.350 回答