简体   繁体   English

Java - 从文本文件中读取数字,并对它们进行排序使负数变为零

[英]Java - Reading numbers from text file, and sorting them makes negative numbers turn to zero

I have a double array我有一个双数组

double[] numbers = new double[1000];
int size = 0;

I then read the numbers from the text file numbers.txt然后我从文本文件numbers.txt读取数字

input = new Scanner(new FileReader("numbers.txt"));
output= new PrintWriter(new FileWriter("sorted.txt"));

while (input.hasNext()) {
    numbers[size] = input.nextDouble();
    size = size + 1;
    if (size == 1000) break;

And then sort them using following:然后使用以下方法对它们进行排序:

numbers = Arrays.stream(numbers)
                .boxed()
                .sorted(Comparator.reverseOrder())
                .mapToDouble(Double::doubleValue)
                .toArray();

And write them to file sorted.txt并将它们写入文件sorted.txt

for (int i = 0; i < size; i++)
    output.println(numbers[i]);

When I try to sort an array that includes negative numbers, for example if numbers.txt contains 5 -3 1 -4 , then sorted.txt will contain 5 1 0 0 .当我尝试对包含负数的数组进行排序时,例如,如果numbers.txt包含5 -3 1 -4 ,则sorted.txt将包含5 1 0 0

I'm relatively a beginner in Java and I'm not sure why this happens.我相对来说是 Java 的初学者,我不确定为什么会发生这种情况。 When I use Array.sort(numbers,0,size) it works well, but I'm trying to sort them in descending order, as this method sorts them in ascending order.当我使用Array.sort(numbers,0,size)它运行良好,但我试图按降序对它们进行排序,因为此方法按升序对它们进行排序。

The problem is that Arrays.stream(numbers) streams the entire array ... including the parts of the array that you didn't put values into.问题是Arrays.stream(numbers)流整个数组......包括你没有放入值的数组部分。 Those parts will contain 0.0 .这些部分将包含0.0

So what is happening is:所以正在发生的是:

  1. You read 4 numbers from the file into the array.您将文件中的 4 个数字读入数组。 This gives you:这给你:

     [5.0, -3.0, 1.0, -4.0, 0.0, 0.0, ..... 0.0]
  2. You sort the array in reverse order:您以相反的顺序对数组进行排序:

     [5.0, 1.0, 0.0, 0.0, ..... 0.0, -1.0, -3.0]
  3. Print out the first 4 elements of the array.打印出数组的前 4 个元素。

     [5.0, 1.0, 0.0, 0.0]

There are various approaches to solving this, including:有多种方法可以解决这个问题,包括:

  • Use an ArrayList<Double> instead of a double[] .使用ArrayList<Double>而不是double[]
  • Pre-initialize all array elements with (say) Double.POSITIVE_INFINITY使用(例如) Double.POSITIVE_INFINITY预初始化所有数组元素
  • Use Arrays.copy to copy the subarray you need before sorting.在排序之前使用Arrays.copy复制您需要的子Arrays.copy
  • Rewrite the stream code to select elements 0 to size - 1 before sorting;重写流代码,在排序前选择0size - 1元素; eg例如

     numbers = Arrays.stream(numbers).limit(size). ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM