Krent
Krent

Reputation: 29

Java - Arrays.sort returns 0

import java.io.*;
import java.util.*;
import java.text.*;

public class aaa {

    public static void main(String args[]) throws IOException {

        Scanner sf = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt"));
        int maxIndx = -1;
        String text[] = new String[1000];
        while (sf.hasNext()) {
            maxIndx++;
            text[maxIndx] = sf.nextLine();
        }

        sf.close();

        double average[] = new double[100];

        for (int j = 0; j <= maxIndx; j++) {
            Scanner sc = new Scanner(text[j]);
            int k = 0;
            while (sc.hasNext()) {
                average[k] = Double.parseDouble(sc.next());
                Arrays.sort(average); //returns 0
                System.out.println(average[k]);
                k++;
            }
        }

    }
}

Without Arrays.sort(average) the program prints out all of the array values normally. However, if I add it in the values are all returned as zero. How do I fix this?

Upvotes: 0

Views: 697

Answers (2)

John Bollinger
John Bollinger

Reputation: 180201

It seems unlikely that what you have written is what you actually want. In particular, you leave the zeroth element of array text containing null, and you sort array average each time you set any element. That indeed causes your trouble, because average has 100 elements, and they are all initialized to 0 when the array is instantiated. If you set any one element nonzero and then sort the array, the non-zero element will be moved to the end, leaving a zero in its place.

It's hard to tell what you actually do want, but generally speaking, one would fill the array with all desired values before sorting it, and if one reserves more space than one needs in that array, then one would sort only the elements that are in use.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533520

This is a lot more complicated than it needs to be, in particular you are sorting the array, every time you set one value in it. This means values you added earlier can be overwritten as you fill up the array.

I suggest you sort the array after all the elements have been added.

Also you know the size the array should be

double average[] = new double[maxIndx+1];

A shorter version might look like

Path path = Paths.get("C:\\temp_Name\\DataGym.in.txt");
double[] nums = Files.lines(path)
                    .mapToDouble(Double.parseDouble)
                    .sorted()
                    .toArray();

Upvotes: 5

Related Questions