简体   繁体   中英

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

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

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 .

I'm relatively a beginner in Java and I'm not sure why this happens. 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.

The problem is that Arrays.stream(numbers) streams the entire array ... including the parts of the array that you didn't put values into. Those parts will contain 0.0 .

So what is happening is:

  1. You read 4 numbers from the file into the array. 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.

     [5.0, 1.0, 0.0, 0.0]

There are various approaches to solving this, including:

  • Use an ArrayList<Double> instead of a double[] .
  • Pre-initialize all array elements with (say) Double.POSITIVE_INFINITY
  • Use Arrays.copy to copy the subarray you need before sorting.
  • Rewrite the stream code to select elements 0 to size - 1 before sorting; eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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